2016-01-10 18 views
3

說完,例如,一個集合命名test和下面的文件是內部ONLY SUBDOCS:蒙戈:如何檢索匹配某些性質

{ 
    "_id" : ObjectId("5692ac4562c824cc5167379f"), 
    "list" : [ 
     { 
      "name" : "elem1", 
      "type" : 1 
     }, 
     { 
      "name" : "elem2", 
      "type" : 2 
     }, 
     { 
      "name" : "elem3", 
      "type" : 1 
     }, 
     { 
      "name" : "elem4", 
      "type" : 3 
     }, 
     { 
      "name" : "elem4", 
      "type" : 2 
     } 
    ] 
} 

比方說,我想找回的只有列表那些與list匹配的子文檔:

  • type = 2

我已經試過以下查詢

db.getCollection('test').find({ 
    '_id': ObjectId("5692ac4562c824cc5167379f"), 
    'list.type': 1 
}) 

但結果我得到包含list子文檔,我想這是因爲裏面list至少有一個文檔這是類型等於 1.

取而代之的是,我有興趣獲得的結果將是list每個子文檔匹配'list.type': 1

{ 
    "_id" : ObjectId("5692ac4562c824cc5167379f"), 
    "list" : [ 
     { 
      "name" : "elem1", 
      "type" : 1 
     }, 
     { 
      "name" : "elem3", 
      "type" : 1 
     } 
    ] 
} 

...所以$$elemMatch是不是我真正需要的,因爲他們只返回第一個匹配的元素。

任何人都知道如何實現我在找的東西?

+1

的可能的複製[只檢索MongoDB中集合的對象陣列中的查詢元件](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an- object-array-in-mongodb-collection) – styvane

+1

@ user3100115不是真的,我不想只有一個元素,我想要所有的匹配元素! – charliebrownie

+4

檢查使用'.aggregate()'方法的答案。 – styvane

回答

0
db.myCol.aggregate([ 
        { $unwind: "$list" }, 
        { $match: { "list.type":1 } }, 
        { $group: { "_id":"$_id", list: {$push:"$list"}} } 
])