使用字段值作为键

时间:2014-07-03 08:08:18

标签: mongodb aggregation-framework

我在做这个查询

db.analytics.aggregate([
    {
        $match: {"event":"USER_SENTIMENT"}
    },
    { $group: {
            _id: {brand:"$data.brandId",sentiment:"$data.sentiment"},
            count: {$sum : 1}
        }
    },
    { $group: {
            _id: "$_id.brand",
            sentiments: {$addToSet : {sentiment:"$_id.sentiment", count:"$count"}}
        }
    }
])

由此产生:

{
    "result" : [ 
        {
            "_id" : 57,
            "sentiments" : [ 
                {
                    "sentiment" : "Meh",
                    "count" : 4
                }
            ]
        }, 
        {
            "_id" : 376,
            "sentiments" : [ 
                {
                    "sentiment" : "Meh",
                    "count" : 1
                }, 
                {
                    "sentiment" : "Happy",
                    "count" : 1
                }, 
                {
                    "sentiment" : "Confused",
                    "count" : 1
                }
            ]
        }
    ],
    "ok" : 1
}

但我想要的是:

[ 
    {
        "_id" : 57,
        "Meh" : 4
    }, 
    {
        "_id" : 376,
        "Meh" : 1,
        "Happy" : 1,
        "Confused" : 1
    }
]

关于如何改变它的任何想法?对我而言,阻止点是将值转换为键。

0 个答案:

没有答案