如何在字段上聚合和汇总MongoDB中相同对象的深层嵌套数组

时间:2017-05-15 10:06:33

标签: mongodb

我有一个mongodb数据如下。

{
"primaryCategory": "Orders",
"sentiment": "POSITIVE",
"date": ISODate("2017-01-12T09:00:00.000Z"),
"commentDetails": [
    {
        "primaryCategory": "Products",
        "sentiment": "NEUTRAL",
        "date": ISODate("2017-01-12T09:00:00.000Z"),
        "commentDetails": [
            {
                "primaryCategory": "Orders",
                "sentiment": "NEGATIVE",
                "date": ISODate("2017-01-12T09:00:00.000Z"),
                "commentDetails": [

                ]
            },
            {
                "primaryCategory": "Responses",
                "sentiment": "POSITIVE",
                "date": ISODate("2017-01-12T09:00:00.000Z"),
                "commentDetails": [

                ]
            }
        ]
    },
    {
        "primaryCategory": "Orders",
        "sentiment": "NEUTRAL",
        "date": ISODate("2017-01-12T09:00:00.000Z"),
        "commentDetails": [
            {
                "primaryCategory": "Products",
                "sentiment": "NEGATIVE",
                "date": ISODate("2017-01-12T09:00:00.000Z"),
                "commentDetails": [

                ]
            },
            {
                "primaryCategory": "Orders",
                "sentiment": "POSITIVE",
                "date": ISODate("2017-01-12T09:00:00.000Z"),
                "commentDetails": [

                ]
            }
        ]
    }
}

在这里,您可以看到下面的对象重复为嵌套数组。

{
"primaryCategory": "Orders",
"sentiment": "POSITIVE",
"date": ISODate("2017-01-12T09:00:00.000Z"),
"commentDetails": []
}

我正在寻找的是,我必须聚合和分组这个类似对象的嵌套数组,以产生如下所示的结果。

[
{primaryCategory:"Orders",sentiment:[POSITIVE:3 /*Sum of all POSITIVE in Orders*/,NEGATIVE:5 /*Sum of all NEGATIVE in Orders*/,NEUTRAL:3 /*Sum of all NEUTRAL in Orders*/]},
{primaryCategory:"Products",sentiment:[POSITIVE:3 /*Sum of all POSITIVE in Products*/,NEGATIVE:5 /*Sum of all NEGATIVE in Products*/,NEUTRAL:3 /*Sum of all NEUTRAL in Products*/]},
{primaryCategory:"Responses",sentiment:[POSITIVE:3 /*Sum of all POSITIVE in Responses*/,NEGATIVE:5 /*Sum of all NEGATIVE in Responses*/,NEUTRAL:3 /*Sum of all NEUTRAL in Responses*/]}
]

这样就可以删除嵌套数组,并通过将字段“primaryCategory”“情绪”

分组来计算总数

我已多次尝试过这项工作而没有运气。 我是MongoDB的初学者,请帮助我实现这个目标。 非常感谢。

0 个答案:

没有答案