【问题标题】:mongodb aggregation lookup pipeline regex matchmongodb聚合查找管道正则表达式匹配
【发布时间】:2020-01-03 19:17:57
【问题描述】:

我正在尝试在聚合管道 $lookup 内进行正则表达式匹配

让我们假设以下查询:

$lookup: {
   from: 'some-collection',
   let: {
      someIds: '$someIds'
   },
   pipeline: [
      {
         $match: {
            $expr: {
               $and: [
                  {
                     $in: ['$someId', '$$someIds']
                  },
                  {
                     $not: {
                        $eq: ['$status', 'archived']
                     }
                  }
               ]
            }
         }
      }
   ]
}

这一切都很好,我可以在多个条件下进行匹配,并且有效。

但是,如果我想使用正则表达式数组添加另一个条件,我无法让它工作

$lookup: {
   from: 'some-collection',
   let: {
      someIds: '$someIds'
   },
   pipeline: [
      {
         $match: {
            $expr: {
               $and: [
                  {
                     $in: ['$someId', '$$someIds']
                  },
                  {
                     $not: {
                        $eq: ['$status', 'archived']
                     }
                  },
                  {
                     $in: ['$some-type', [/type1/, /type2/]]
                  }
               ]
            }
         }
      }
   ]
}

为什么这不起作用?正如我从documentation 所了解的那样,我应该能够在$in 运算符中以这种方式使用正则表达式,并且我可以确认它有效,因为我们在其他地方使用它。但是嵌套在$lookuppipeline 中却没有。

这是一个错误还是我忽略了什么?还有其他方法可以进行这种正则表达式匹配吗?

【问题讨论】:

    标签: regex mongodb aggregation-framework


    【解决方案1】:

    显然,问题似乎是我试图在 $expr 运算符内进行正则表达式匹配,我不确定它为什么不起作用,而且我在文档中找不到任何内容。

    但是通过将它移动到管道中的单独匹配它可以工作。

    $lookup: {
       from: 'some-collection',
       let: {
          someIds: '$someIds'
       },
       pipeline: [
          {
             $match: {
                $expr: {
                   $and: [
                      {
                         $in: ['$someId', '$$someIds']
                      },
                      {
                         $not: {
                            $eq: ['$status', 'archived']
                         }
                      }
                   ]
                }
             }
          },
          {
             $match: {
                some-type: {
                   $in: [/type1/, /type2/]
                }
             }
          }
       ]
    }
    

    如果有人可以详细说明为什么会这样,请随意

    【讨论】:

    • 放在同一个比赛阶段{ $match: { "some-type": { $in: [/type1/, /type2/] }, $expr: { $and: [ { $in: ['$someId', '$$someIds'] }, { $not: { $eq: ['$status', 'archived'] } } ] } } }
    猜你喜欢
    • 2023-02-25
    • 2020-06-13
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多