问题描述
我有一个包含嵌套数组数据的文档.我无可救药地尝试使用$elemMatch
过滤数据,但我无法弄清为什么它不起作用.
I have a document containing nested array data. I tried hopelessly to filter the data using $elemMatch
but I cannot figure out why it is not working.
{
'id' : 1,
'name' : 'test',
'modules' : [
{
name: 'foo',
mandatory: false,
group: [
{
name: g1
}]
},
{
name: 'bar',
mandatory: false,
group: [
{
name: g2
}]
}]
}
我尝试使用此查询:
db.test.find(
{
modules: {
$elemMatch: {
name: "foo",
}
}
}
但是它一直返回所有模块.如果我使用mandatory: true
,则不返回任何内容,这似乎表明它可以工作.知道我在做什么错吗?谢谢!
But it keeps returning all the modules. If I use mandatory: true
it returns nothing, which seems to indicates it works. Any idea what am I doing wrong? Thanks!
推荐答案
您的查询只是返回所有包含modules
元素的文档,其中name == 'foo'
.要使用 $elemMatch
来过滤输出,您需要在find
调用的投影参数中使用它,而不是查询的一部分:
Your query is simply returning all docs that contain a modules
element where name == 'foo'
. To use $elemMatch
to filter the output, you need to use it in the projection argument of the find
call instead of part of the query:
db.test.find({}, {modules: {$elemMatch: {name: 'foo'}}})
要结合这两个概念,可以使用$
引用查询中匹配的数组元素的索引:
To combine both concepts, you can reference the index of the array element matched in the query with $
:
db.test.find({modules: {$elemMatch: {name: 'foo'}}}, {'modules.$': 1})
这两种方法都会返回:
{
"_id": ObjectId("..."),
"modules": [
{
"name": "foo",
"mandatory": false,
"group": [
{
"name": "g1"
}
]
}
]
}
如果您需要输出中包含其他字段,请将其添加到投影对象(例如name: 1
).
If you need other fields included in the output, add them to the projection object (e.g. name: 1
).
这篇关于使用elemMatch进行MongoDB查询以获取嵌套数组数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!