【问题标题】:How a pass a dynamic string to $regex in mongodb aggregation如何在 mongodb 聚合中将动态字符串传递给 $regex
【发布时间】:2021-11-24 05:04:31
【问题描述】:

我有两个系列,一个是广告系列,另一个是订单。我必须过滤每个广告系列的订单。所以我正在做的是获取所有广告系列,然后查找符合某些特定条件的订单。

[
 { 
   $match: { type: 'FOLLOWUP' } 
 },
 {
   $lookup: {
     from: 'orders',
     as: 'orders',
     pipeline: [
       {
          $match: {
             'title': { $regex: '$keyword', $options: 'i' },
          }
       }
     ]
   }
 }
]

在上面的示例中,每个广告系列都包含 keyword 类型为 string 的字段。因此,我必须过滤所有包含keyword 的广告系列的所有订单,每个广告系列都有不同的关键字。如何将动态引用传递给 $regex,如果我使用的是硬编码字符串,它可以正常工作,但对于传递引用 ('$keyword'),它不起作用。

任何帮助将不胜感激。

【问题讨论】:

    标签: node.js mongodb aggregation-framework aggregate aggregation


    【解决方案1】:

    你可以试试$regexMatch聚合表达式运算符,

    • letkeyword 从广告系列集合传递到查找
    • $regexMatch 聚合表达式运算符将输入作为title 和正则表达式作为keyword 引用来自let 使用$$ 符号
    [
      { $match: { type: "FOLLOWUP" } },
      {
        $lookup: {
          from: "orders",
          as: "orders",
          let: { keyword: "$keyword" },
          pipeline: [
            {
              $match: {
                $expr: {
                  $regexMatch: {
                    input: "$title",
                    regex: "$$keyword",
                    options: "i"
                  }
                }
              }
            }
          ]
        }
      }
    ]
    

    Playground

    【讨论】:

      猜你喜欢
      • 2021-11-23
      • 2018-09-15
      • 2021-07-12
      • 1970-01-01
      • 2015-07-17
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 2022-10-21
      相关资源
      最近更新 更多