MongoDB的嵌套聚合管道

4

我有一个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" }

    }
},

但是输出只是每个元素的一个平坦数组。是否有一种方法可以使聚合产生像上面那样的嵌套对象?

1个回答

5

首先,您可以按eventIDupdate进行分组,然后按eventID进行分组,同时将update使用$push放入一个数组中。

{$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需要改为$_id.eventID。 - Squidinker
...但是你的解决方案恰好符合我的需求。谢谢! - Squidinker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接