【问题标题】:Using $match to query from different arrays with the same key value使用 $match 从具有相同键值的不同数组中查询
【发布时间】:2020-08-14 18:05:39
【问题描述】:

假设我有两个文档的这个简单 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
        }
    }
])

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

【问题讨论】:

    标签: mongodb express aggregation-framework


    【解决方案1】:

    如果我的要求正确。在.find() 查询中使用dot(.) notation 并以projection 作为第二个参数怎么样。

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

    【讨论】:

    • 让我试试这个,我会回复你的!
    • @BrioTech Playground link 看看这是不是你要找的东西。
    • 我已接受您的回答。简单明了。看了你的解决方案后,我可能想多了我的问题哈哈
    • 另外,感谢您帮助我发现 mongo 游乐场!
    猜你喜欢
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    • 2017-04-23
    • 2014-03-12
    • 1970-01-01
    相关资源
    最近更新 更多