2016-09-06 89 views
0

我想寫一個蒙戈DB查詢,我做到以下幾點,蒙戈DB - 集團BY和HAVING實施

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 

我試圖做到以下幾點,

產業是集名稱,

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

      ]) 

我得到一個空的結果。請建議我能做些什麼

回答

0

好吧,我沒有人接聽。但是,在此期間,我設法弄清楚了自己。下面張貼的答案,

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

從本質上講,使用unwind無論你必須遍歷數組(子文檔的列表)。至少對我而言,這是一次富有成效的學習。