假设我有这样的文件:
{
"_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的文档。
答案 0 :(得分:2)
您可以使用$elemMatch
查询运算符来匹配数组中的多个字段
db.collection.find({ myArray: { $elemMatch: { address: 'abc', role: 'output' }}})