MongoDB聚合查询中展开后与OR子句匹配

MongoDB聚合查询中展开后与OR子句匹配,mongodb,mongodb-query,aggregate,Mongodb,Mongodb Query,Aggregate,我有这样一个MongoDB聚合查询 [{ "$match" : { "isDeleted" : false } } , { "$match" : { "$or" : [{ "arrayCol.col_1" : "Yes", "arrayCol.subArrCol.col_2" : 10 }, { "arrayCol.subArrCol.col_3&

我有这样一个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"
            }
        ]
    }
}
你可以试试

  • $unwind
    解构
    列3
    列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" }