例如,有一个名为 test
的集合,其中包含以下文档:
{
"_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
中匹配的那些子文档的列表:
类型 = 2
。
我尝试了以下查询:
db.getCollection('test').find({
'_id': ObjectId("5692ac4562c824cc5167379f"),
'list.type': 1
})
但我得到的结果包含 list
中的 every 子文档,我猜这是因为 list
中至少有一个文档是输入等于 1。
取而代之的是,我想获得的结果是 list
中匹配 'list.type': 1
的每个子文档:
{
"_id" : ObjectId("5692ac4562c824cc5167379f"),
"list" : [
{
"name" : "elem1",
"type" : 1
},
{
"name" : "elem3",
"type" : 1
}
]
}
...所以 $
和 $elemMatch
并不是我真正想要的,因为它们只返回第一个匹配的元素。
有人知道如何实现我的目标吗?
最佳答案
db.myCol.aggregate([
{ $unwind: "$list" },
{ $match: { "list.type":1 } },
{ $group: { "_id":"$_id", list: {$push:"$list"}} }
])
关于mongodb - 蒙戈 : how to retrieve ONLY subdocs that match certain properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34710018/