【问题标题】:Match with OR clause after Unwind in MongoDB aggregate query在 MongoDB 聚合查询中 Unwind 后与 OR 子句匹配
【发布时间】:2020-09-20 12:55:15
【问题描述】:

我有一个这样的 MongoDB 聚合查询

[{ "$match" : { "isDeleted" : false } }
, { "$match" : { "$or" : [{ "arrayCol.col_1" : "Yes", "arrayCol.subArrCol.col_2" : 10 }, { "arrayCol.subArrCol.col_3" : 2000 }] } }
, { "$project" : { "_id" : 0, "col_0" : "$col_0", "col_1" : "$arrayCol.col_1", "col_2" : "$arrayCol.subArrCol.col_2", "col_3" : "$arrayCol.subArrCol.col_3" } }]

目前正在返回如下 2 个文档

/* 1 */
{
    "col_0" : "xyz",
    "col_1" : "Yes",
    "col_2" : [
        10
    ],
    "col_3" : [
        2013,
        1995
    ]
},

/* 2 */
{
    "col_0" : "pqr",
    "col_1" : "Yes",
    "col_2" : [
        9,
        10
    ],
    "col_3" : [
        2000,
        2000
    ]
}

现在我想同时展开“col_2”和“col_3”,但它应该只返回那些像以前一样的文档,即那些 col_2 = 10 或 col_3 = 2000 的文档。

我的预期结果集如下,

/* 1 */
{
    "col_0" : "xyz",
    "col_1" : "Yes",
    "col_2" : 10,
    "col_3" : 2013
},

/* 2 */
{
    "col_0" : "pqr",
    "col_1" : "Yes",
    "col_2" : 9,
    "col_3" : 2000
}
/* 3 */
{
    "col_0" : "pqr",
    "col_1" : "Yes",
    "col_2" : 10,
    "col_3" : 2000
}

如果匹配条件是 AND 子句,那么我可以在展开后再次添加相同的匹配条件以消除错误值。 但是我如何在 OR 子句中解决这个问题/有人可以帮忙吗? 我是 MongoDB 新手。

我收藏的文档如下,

{
    "_id": "1234-5f33-4703-be7f-3ea679951af3",
    "col_0": "xyz",
    "arrayCol": {
        "col_1": "Yes",
        "subArrCol": [
            {
                "col_2": 10,
                "col_3": 2013
            },
            {
                "col_3": 1995
            }
        ]
    }
},
{
    "_id": "5678-5f33-4703-be7f-3ea679951af3",
    "col_0": "pqr",
    "arrayCol": {
        "col_1": "Yes",
        "subArrCol": [
            {
                "col_2": 9,
                "col_3": 2000
            },
            {
                "col_2": 10,
                "col_3": 2000,
                "col_4": "abc"
            }
        ]
    }
}

【问题讨论】:

  • 集合和预期结果集均已添加。为了更清晰,查询也有所改变。请检查

标签: mongodb mongodb-query aggregate


【解决方案1】:

你可以试试,

  • $unwind 解构 col_3col_2 数组
  • $match你的条件
  • $group root 删除重复文件
  • $replaceWith 将 _id 对象替换为根文档
  { $match: { ... } }, //skipped 
  { $project: { ... } }, //skipped 

  { $unwind: "$col_3" },
  { $unwind: "$col_2" },
  {
    $match: {
      $or: [
        {
          col_1: "Yes",
          col_2: 10
        },
        { col_3: 2000 }
      ]
    }
  },
  { $group: { _id: "$$ROOT" } },
  { $replaceWith: "$_id" }

Playground

【讨论】:

    猜你喜欢
    • 2021-11-12
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    相关资源
    最近更新 更多