【发布时间】:2016-11-12 00:21:27
【问题描述】:
我有一个 mongodb 集合,其中包含以下格式的大量文档:
{
"_id": {
"$oid": "581f9eae05711c35f461d779"
},
"eventID": "Illinois84bc00edc91c24a95573",
"type": "voteup",
"update": "f3a44be56669e01cf02ed685c97451ba",
"count": 1,
}
我需要能够从我的服务器对集合运行聚合并返回一个 JSON 对象:
按 eventID 对数据进行分组(有很多 eventID),然后按更新对这些组中的文档进行分组(有很多更新,每个更新都与一个 eventID 相关联),然后对于每个 eventID/更新组,对“计数”求和“voteup”和“votedown”类型的每个文档的值。
所以实际输出可能如下所示:
{
"events": [
// array of objects, one for each unique eventID
{
"eventID": "Idaho4532543trt3424f",
"updates": [
// array of objects, one for each unique update
{
"update": "rh43782ty738tywuioty34",
"voteup": 12, // the number of documents with that eventID/update which are type "voteup"
"votedown": 1 // the number of documents with that eventID/update which are type "voteudown"
},
{
"update": "hfu89h834hw8uoglthyw78",
"voteup": 2,
"votedown": 32
},
{
"update": "as09g8fgdsiuhgofhdosug",
"voteup": 123,
"votedown": 5
}
]
},
// here's another event...
{
"eventID": "Texas38tr943uytwo9grs",
"updates": [
{
"update": "2ty738tywuioty34rh4378",
"voteup": 0,
"votedown": 1
},
{
"update": "34hw8uoglthyw78hfu89hv",
"voteup": 22,
"votedown": 72
},
{
"update": "dsiuhgofhdosugas09g8fg",
"voteup": 67,
"votedown": 11
}
]
}
]
}
下面的任务是计算有多少 eventID/update/type 文档:
{
$group: {
_id: { eventID: "$eventName", updateID: "$update", sentiment: "$type" }
}
},
但输出只是每个的平面数组。有没有办法让聚合产生一个像上面那样的嵌套对象?
【问题讨论】:
标签: mongodb aggregation-framework