我有一个mongodb集合,其中有很多文档,格式如下:
{
"_id": {
"$oid": "581f9eae05711c35f461d779"
},
"eventID": "Illinois84bc00edc91c24a95573",
"type": "voteup",
"update": "f3a44be56669e01cf02ed685c97451ba",
"count": 1,
}
我需要能够在我的服务器上对集合运行聚合操作,并返回一个JSON对象,其中:
按eventID(有许多eventIDs)对数据进行分组,然后将这些组中的文档按update(有许多updates,每个update都与一个eventID相关联)进行分组,然后对于每个eventID / Update组,汇总“voteup”和“votedown”类型的每个文档的“count”值。
因此,实际输出可能如下所示:
{
"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" }
}
},
但是输出只是每个元素的一个平坦数组。是否有一种方法可以使聚合产生像上面那样的嵌套对象?