mongodb的嵌套聚合管道
我有一个mongodb集合,其中包含以下格式的大量文档:mongodb的嵌套聚合管道,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我有一个mongodb集合,其中包含以下格式的大量文档: { "_id": { "$oid": "581f9eae05711c35f461d779" }, "eventID": "Illinois84bc00edc91c24a95573", "type": "voteup", "update": "f3a44be56669e01cf02ed685c97451ba", "count": 1, } 我需要能够从集合上的服务器运行聚合,
{
"_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" }
}
},
但输出只是每个元素的平面数组。有没有办法让aggregate生成一个像上面那样的嵌套对象?首先可以在
eventID
和update
上分组,然后在eventID
上分组,同时执行$push
将update
放入数组中
{$group: {
_id: {eventID: '$eventID', update: '$update'},
voteup: {$sum: {$cond: [
{$eq: ['$type', {$literal: 'voteup'}]},
1,
0
]}},
votedown: {$sum: {$cond: [
{$eq: ['$type', {$literal: 'voteup'}]},
0,
1
]}}
}},
{$group: {
_id: {eventID: '$_id.eventID'},
updates: {$push: {
update: '$_id.update',
voteup: '$voteup',
votedown: '$votedown'
}}
}}
其中有一个小错误;在第二个$group中,$id.eventID需要是$\u id.eventID…但是您的解决方案正是我想要的。非常感谢。