假设我有这样的文件:
{
"_id", "1",
"myarray": [
{
"address": "abc",
"role": "input",
}
{
"address": "def",
"role": "output",
}
]
},
{
"_id", "2",
"myarray": [
{
"address": "xyz",
"role": "input",
}
{
"address": "abc",
"role": "output",
}
]
}
我想返回文件,其中myarray.address是abc并输出myarray.role,但不是文件存在myarray.address ='abc'并且存在myarray.role ='output',但文件中存在myarray数组元素:
address: "abc",
role: "output"
使用上面的示例,我只想要_id = 2的文档。
您可以使用$elemMatch
查询运算符来匹配数组中的多个字段
db.collection.find({ myArray: { $elemMatch: { address: 'abc', role: 'output' }}})