MongoDB - 按几个数组元素过滤

问题描述 投票:2回答:1

假设我有这样的文件:

{
    "_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的文档。

mongodb mongodb-query
1个回答
2
投票

您可以使用$elemMatch查询运算符来匹配数组中的多个字段

db.collection.find({ myArray: { $elemMatch: { address: 'abc', role: 'output' }}})
© www.soinside.com 2019 - 2024. All rights reserved.