分组后的文档样本。
[
{
"_id": {
workhour: 1
},
totalChats: 156
},
{
"_id": {
workhour: 0
},
totalChats: 36
}
]
你好!我怎么才能找到这2个对象的百分比呢,最后的结果应该是。
[
{
"totalChats": 192,
"workhour0": 19,
"workhour1": 81
}
]
谢谢您!
你需要至少有MongoDB的版本。4.0
做到这一点,因为使 {workhour : 1}
形成 workhour1
你需要连接 workhour
连串 1
因此,要转换 1
到字符串,你需要使用 $toString
只有在>=中才有。4.0
. 你需要在你的 $group
阶段 :
db.collection.aggregate([
{
$group: {
_id: "", // Group without any condition will group all docs
docs: { $push: { workhour: "$_id.workhour", totalChats: "$totalChats" } // push {workhour :...,totalChats:...} objects to data array
},
totalChats: { $sum: "$totalChats" } // Sum-up `totalChats` across all docs
}
},
{
$project: {
_id: 0,
totalChats: 1,
data: {
$arrayToObject: { // Converts [{k :..., v:...}, {k :..., v:...}] into {k : v, k:v }
$map: { // Pushing objects {k:...,v:...} to an array
input: "$docs",
in: { k: { $concat: [ "workhour", { $toString: "$$this.workhour" } ] }, v: { $multiply: [ { $divide: [ "$$this.totalChats", "$totalChats" ] }, 100 ] } }
}
}
}
}
},
/** Replace root of doc with newly created object */
{
$replaceRoot: { newRoot: { $mergeObjects: [ "$data", { totalChats: "$totalChats" } ] } }
}
])
阶段:测试: mongoplayground
参考文献 : 聚合运营商
注意: 你应该保持 18.75
原样,而不是将其转换为 19
&amp。81.25
至 81
以免造成任何不确定性。