首页 > 解决方案 > 使用 $match 从具有相同键值的不同数组中查询

问题描述

假设我有两个文档的这个简单 JSON 数据,两个文档都有两个不同的数组,即carPoliciespaPolicies​​ . 在这些数组中,对象被命名为policy其中包含键“代理”,其值为“47”。

{
    "_id": {
        "$oid": "some_id"
    },
    "name": "qwe",
    "password": "pw",
    "carPolicies": [
        {
            "policy": { 
                "agent": "47"
            }
        },
        {
            "policy": {                   
                "agent": "47"
            }
        }
    ],
    "paPolicies": [
        {
            "policy": {                  
                "agent": "47"
            }
        },
        {
            "policy": {                   
                "agent": "47"
            }
        }
    ]
}


{
    "_id": {
        "$oid": "some_id"
    },
    "name": "rty",
    "password": "wp",
    "carPolicies": [
        {
            "policy": { 
                "agent": "47"
            }
        },
        {
            "policy": {                   
                "agent": "47"
            }
        }
    ],
    "paPolicies": [
        {
            "policy": {                  
                "agent": "47"
            }
        },
        {
            "policy": {                   
                "agent": "47"
            }
        }
    ]
}

使用 mongoDB 的 $match 运算符,我如何提出一个查询,如果代理值在任一数组中为 47,它会返回文档的名称?

这是我目前拥有的:

db.collection('users').aggregate([
    // Get just the docs that contain an agent element where agent is === req.params.name
    {$match: {$or: [{'paPolicies.policy.agent': req.params.name}, {'carPolicies.policy.agent': req.params.name}]} }, 
    {
        $project: {
            policy: {
                $filter: {
// how to do an 'or' operator at 'input' so it can be input: '$paPolicies.policy || $carPolicies.policy' 
                    input: '$paPolicies.policy',
                    as: 'police',
                    cond: { $eq: ['$$police.agent', req.params.name]}
                }
            },
            _id: 1, name: 1
        }
    }
])

我知道上面的代码是错误的,但我觉得这是我目前能找到的最接近解决方案的方法,希望能对我想要实现的目标有所了解。

标签: mongodbexpressaggregation-framework

解决方案


如果我得到正确的要求。在以投影作为第二个参数的查询中使用dot(.)符号怎么样。.find()

db.collection.find({
  $or: [
    {
      "carPolicies.policy.agent": "47"
    },
    {
      "paPolicies.policy.agent": "47"
    }
  ]
},
{
  "_id": 1,
  "name": 1
})

推荐阅读