2016-08-31 140 views
1

在我的Mongo中擁有以下文檔我試圖獲取具有指定id的對象。這是我的Mongo文檔。 蒙戈版本:2.6在MongoDB中只檢索嵌套數組中的查詢對象

{ 
    "_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" 
         } 
        ] 
       } 
      ] 
     } 
    ] 
} 

我在尋找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 documentshttps://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-ed文檔的條件的最終」$匹配「。

+1

非常感謝。很有幫助。 –