【发布时间】:2016-04-15 01:58:20
【问题描述】:
例如,有一个名为 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 中匹配的子文档的列表:
-
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 并不是我真正想要的,因为它们只返回第一个匹配元素。
有人知道如何实现我的目标吗?
【问题讨论】:
-
@user3100115 不是真的,我不想要只有一个元素,我想要所有匹配的元素!!!
-
检查使用
.aggregate()方法的答案。
标签: mongodb mongoose mongodb-query