MongoDB计数(如果存在)并按不同的数组值分组

时间:2017-07-20 16:05:09

标签: javascript mongodb

我的收藏品看起来像这样:

{
    "_id" : 1,
    "category" : [
         {
           "name": "category1"
         },
         {
           "name": "category2"
         }
    ],
    "event": [
               {
                 type: "house"
               },
               {
                 type: "mouse"
               }
             ]
},

{
    "_id" : 2,
    "category" : [
         {
           "name": "category2"
         },
         {
           "name": "category3"
         }
    ]
},

{
    "_id" : 3,
    "category" : [
         {
           "name": "category3"
         },
         {
           "name": "category1"
         }
    ],
        "event": [
           {
             type: "mouse"
           }
         ]
}

我需要按不同的类别名称类型进行分组,并计算是否存在可获取文档的事件:

{ "category1": total_count: 2,
  "category2": total_count: 0,
  "category3": total_count: 1}

任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:1)

试试这个,它对我有用:

db.getCollection('coll').aggregate([
{$unwind: "$category"},
{$group :{
    _id : "$category.name",   
    total_count : {$sum : 1}
 }
}])