mongodb聚合查找管道正则表达式匹配

时间:2020-01-03 10:50:27

标签: regex mongodb aggregation-framework

我正在尝试在聚合管道$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运算符内以这种方式使用正则表达式,并且由于我们在其他地方使用过它,因此我可以确认它是否有效。但是,它嵌套在$lookup管道中。

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

1 个答案:

答案 0 :(得分:0)

很明显,问题似乎是我试图在$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/]
            }
         }
      }
   ]
}

如果有人能详细说明为什么会出现这种情况