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
是不是我真正需要的,因爲他們只返回第一個匹配的元素。
任何人都知道如何實現我在找的東西?
的可能的複製[只檢索MongoDB中集合的對象陣列中的查詢元件](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an- object-array-in-mongodb-collection) – styvane
@ user3100115不是真的,我不想只有一個元素,我想要所有的匹配元素! – charliebrownie
檢查使用'.aggregate()'方法的答案。 – styvane