Mongo DB - 分组和实施

时间:2016-09-06 20:52:00

标签: mongodb aggregation-framework

我正在尝试编写一个Mongo数据库查询,其中我执行以下操作,

JSON列表 - 代表我的集合中的文档,

行业[]:

{ 
    "_id" : ObjectId("57aa6058be0c853c8cee34cd"), 
    "options": {
        "paramList" : [
            {
                "name" : "industryCategory",
                "value" : "Travel",
                "mandatory" : true
            },
            {
                "name" : "someOtherThing",
                "value" : "dontMind",
                "mandatory" : true
            }
        ]
    }
    "mostRecent" : true
},
{ 
    "_id" : ObjectId("57aa6058be0c853c8cee34cd"), 
    "options": {
        "paramList" : [
            {
                "name" : "industryCategory",
                "value" : "Dining",
                "mandatory" : true
            },
            {
                "name" : "someOtherThing",
                "value" : "dontMind",
                "mandatory" : true
            }
        ]
    }
    "mostRecent" : true
},
{ 
    "_id" : ObjectId("57aa6058be0c853c8cee34cd"), 
    "options": {
        "paramList" : [
            {
                "name" : "industryCategory",
                "value" : "Travel",
                "mandatory" : true
            },
            {
                "name" : "someOtherThing",
                "value" : "dontMind",
                "mandatory" : true
            }
        ]
    }
    "mostRecent" : true
}

我正在尝试分组并获取那些paramList的值的计数 - 其中name是industryCategory的值。基本上,我正在寻找的输出是这样的,

Travel: 2
Dining: 1

我正在尝试执行以下操作,

Industry是集合的名称,

db.Industry.aggregate (
          [
            {$match: {mostRecent: true}},
            {$group: {
              _id: '$options.paramList.value', 
              count: {$sum: 1}
              }},
              {$match: {'options.paramList.name': 'industryCategory'}}

          ])

我得到一个空洞的结果。请建议我能做什么

1 个答案:

答案 0 :(得分:0)

好吧,我没有人回答。但是,与此同时,我设法弄明白了。发布以下答案,

aggregate (
          [
            {"$match": {mostRecent: true}},
            {"$unwind" : "$options.paramList"},
            {"$group" :
              {
                _id: "$options.paramList.value",
                count: {$sum : 1}
              }
            }
          ]

基本上,只要在数组(子文档列表)上进行迭代,就可以使用unwind。这对我来说是一次富有成效的学习。

相关问题