2016-08-31 143 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

非常感谢。很有帮助。 –