首页 > 解决方案 > mongodb聚合查找管道正则表达式匹配

问题描述

我正在尝试在聚合管道中进行正则表达式匹配$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/]]
                  }
               ]
            }
         }
      }
   ]
}

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

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

标签: regexmongodbaggregation-framework

解决方案


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

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


推荐阅读