【发布时间】:2018-08-09 19:05:01
【问题描述】:
如何向集合中添加一个在 MongoDB 中累积值集合字段的文档?
我有一个 MongoDB 集合,其中包含以下格式的文档:
{
"_id" : 3876435465554,
"title" : "xxx",
"category" : "xxx",
...
}
所以期望的结果是:
{ "_id" : "All", "num" : 28 } // <- This is the document that I want include in the output
{ "_id" : "xxx", "num" : 11 }
{ "_id" : "yyy", "num" : 8 }
{ "_id" : "zzz", "num" : 9 }
到目前为止,我已经尝试过:
db.collection.aggregate([
{ $project: { title:1, category:1} },
{ $group: {
_id: { _id:"$category"},
num: { $sum: 1 }
} },
{ $project: { _id:"$_id._id", num:1} },
{ $sort: { _id:1} }
])
但这只会产生文档没有“全部”文档:
{ "_id" : "xxx", "num" : 11 }
{ "_id" : "yyy", "num" : 8 }
{ "_id" : "zzz", "num" : 9 }
我不知道如何将“全部”文档与所有“num”值的总和相加。
注意:将 2 次调用链接到 aggregates 我能够在程序中获得期望的输出,但我们的想法是只使用一个 aggregate 来获得输出。
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework