在mongo中计算文档中的重复对象

时间:2019-05-17 12:09:39

标签: mongodb codeigniter-3

我有这种类型的数据,我想根据字符串来计算重复的对象

{

    "version":"2.0",
    "type":"DevicesSeen",
    "data":{
        "observations":[
            {
                "manufacturer":"Apple"
            },
            {
                "manufacturer":"GUANGDONG OPPO MOBILE..."
            },
            {
                "manufacturer":"Apple"
            }
        ]
    }

}

我要制造商的数量 例 苹果:2 三星:1

1 个答案:

答案 0 :(得分:1)

尝试这个

db.collection.aggregate([
    {
        $unwind: "$data.observations"
    },
    {
        $group: {
            _id: "$data.observations.manufacturer",
            counts: {$sum :1}
        }
    }
 ])

结果如下:

/* 1 */
{
    "_id" : "GUANGDONG OPPO MOBILE...",
    "counts" : 1
},

/* 2 */
{
    "_id" : "Apple",
    "counts" : 2
}