2016-09-06 2 views
0

나는 다음을 수행합니다 몽고 DB 쿼리를 작성하는 노력하고있어몽고 DB - 그룹에 의해 갖는 구현

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 
} 

나는 이름이 industryCategory 인 paramList - 값에 대해 값의 개수를 그룹화하려고합니다. 기본적으로 내가 찾고 있어요 출력은 다음과 같이,

산업 컬렉션의 이름 난 다음을 수행하기 위해 노력하고있어

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을 사용하여 게시. 적어도 나를 위해 생산적인 학습을 해왔습니다.