如何在mongoDB查询中添加表示总数字的字段



我有一个mongodb查询

[  
{$group: { 
_id: '$status',
count: {$sum: NumberInt(1)}
}}
]

查询返回以下结果:

[
{ _id: "A", count: 22 },
{ _id: "B", count: 33 },
{ _id: "C", count: 44 }
]

基于以上内容,我需要添加一个新字段";totalCount";(例如22+33+44=99(如下:

[
{ _id: "A", count: 22, totalCount: 99 },
{ _id: "B", count: 33, totalCount: 99 },
{ _id: "C", count: 44, totalCount: 99 }
]

我们非常感谢任何帮助或线索。

您必须使用$facet阶段来创建多个聚合实例,计算不同阶段的总计数,并最终合并为单个输出。

db.collection.aggregate([
{
"$facet": {
"totalCount": [
{
"$group": {
"_id": null,
"totalCount": {
"$sum": "$count"
}
},

},

],
"root": [
{
"$replaceRoot": {
"newRoot": "$$ROOT"
}
},

]
}
},
{
"$unwind": "$root"
},
{
"$replaceRoot": {
"newRoot": {
"$mergeObjects": [
"$root",
{
"$arrayElemAt": [
"$totalCount",
0
]
}
],

}
}
},

])

Mongo示例执行

最新更新