2013-03-15 83 views
1

我有如下文件:如何检索MongoDB中数组中存在的所有匹配元素?

{ 
    name: "testing", 
    place:"London", 
    documents: [ 
         { 
          x:1, 
          y:2, 
         }, 
         { 
          x:1, 
          y:3, 
         }, 
         { 
          x:4, 
          y:3, 
         } 
      ] 
    } 

我想检索所有匹配的文件,即我想O/P在以下格式:

{ 
    name: "testing", 
    place:"London", 
    documents: [ 
         { 
          x:1, 
          y:2, 
         }, 
         { 
          x:1, 
          y:3, 
         } 

      ] 
    } 

我曾尝试是:

db.test.find({"documents.x": 1},{_id: 0, documents: {$elemMatch: {x: 1}}}); 

但是,它只提供第一个条目。

+0

的可能重复的[MongoDB的:选择匹配子集合的元件](http://stackoverflow.com/questions/15415023/mongodb-选择匹配的元素 - 的-子集合) – JohnnyHK 2013-03-15 13:08:10

回答

3

正如JohnnyHK说,MongoDB: select matched elements of subcollection答案解释得很好。

在你的情况,总应该是这样的:

(注:第一场比赛是不是绝对必要的,但它在性能方面帮助(可使用指数)和内存使用($放松对有限集)

> db.xx.aggregate([ 
...  // find the relevant documents in the collection 
...  // uses index, if defined on documents.x 
...  { $match: { documents: { $elemMatch: { "x": 1 } } } }, 
...  // flatten array documennts 
...  { $unwind : "$documents" }, 
...  // match for elements, "documents" is no longer an array 
...  { $match: { "documents.x" : 1 } }, 
...  // re-create documents array 
...  { $group : { _id : "$_id", documents : { $addToSet : "$documents" } }} 
... ]); 
{ 
    "result" : [ 
     { 
      "_id" : ObjectId("515e2e6657a0887a97cc8d1a"), 
      "documents" : [ 
       { 
        "x" : 1, 
        "y" : 3 
       }, 
       { 
        "x" : 1, 
        "y" : 2 
       } 
      ] 
     } 
    ], 
    "ok" : 1 
} 

有关集合()的详细信息,请参阅http://docs.mongodb.org/manual/applications/aggregation/

相关问题