2016-08-31 2 views
1

다음 문건이 내 Mongo에서 지정된 ID로 객체를 가져 오려고합니다. 여기 몽고 문서입니다. 몽고 버전 : 2.6MongoDB의 중첩 된 배열에서 질의 된 객체 만 검색하십시오.

{ 
    "_id" : ObjectId("57c1ae9ac1bd31d4eb4d546d"), 
    "footers" : [ 
     { 
      "type" : "web", 
      "rows" : [ 
       { 
        "id" : "abc", 
        "elements" : [ 
         { 
          "id" : "def", 
          "type" : "image", 
          "url" : "http://example.com" 
         }, 
         { 
          "id" : "ghi", 
          "type" : "image", 
          "url" : "http://example.com" 
         } 
        ] 
       } 
      ] 
     } 
    ] 
} 

나는 "DEF"ID를 가진 개체를 찾고 있어요, 나는이 결과를 가져올 : 내가 노력 코드의 예를 인용 아래

{ 
    "id" : "def", 
    "type" : "image", 
    "url" : "http://example.com" 
} 

을 이 객체를 검색합니다.

db.getCollection('myCollection').aggregate([ 
    {"$match": { 
     "footers.rows.elements.id": "def" 
    }}, 
    {"$group": { 
     "_id": "$footers.rows.elements" 
    }} 
]) 

그리고 그 결과는 다음과 같습니다

{ 
    "_id" : [ 
     [ 
      [ 
       { 
        "id" : "def", 
        "type" : "image", 
        "url" : "http://example.com" 
       }, 
       { 
        "id" : "ghi", 
        "type" : "image", 
        "url" : "http://example.com" 
       } 
      ] 
     ] 
    ] 
} 

어떤 제안?

답변

2

"$unwind"을 사용해야합니다.

자세한 내용은 Mongodb unwind nested documents (https://stackoverflow.com/a/12241733/224743이가 MongoDB를 작동해야 지정 2.2) 특정 예를 들어

와 함께 당신을 도울 것이 답변, 당신은 같은 것을 할 수있는 :

db.getCollection('myCollection').aggregate([ 
    {"$match" : { "footers.rows.elements.id": "def" }}, 
    {"$unwind" : "$footers"}, 
    {"$unwind" : "$footers.rows"}, 
    {"$unwind" : "$footers.rows.elements"}, 
    {"$group" : { "_id": "$footers.rows.elements" }}, 
    {"$match" : { "_id.id": "def" }} 
]); 

공지 다중를 " $ unwind "chainings과 $ unwind-ed 문서에 대한 조건을 다시 적용하는 데 필요한 마지막"$ match "도 포함됩니다.

+1

고마워요. 매우 도움이됩니다. –