在 mongodb 聚合中使用 $expr 内部的 $regex

gan*_*esh 3 regex mongodb mongodb-query aggregation-framework expr

我的文档如下所示

doc = {
    name: 'abc',
    age:20
}
Run Code Online (Sandbox Code Playgroud)

我的查询看起来像

{ $expr: {$and:[{ $gt:[ "$age",  10 ] },
                { $regex:["$name",'ab']}
               ]
          }
} }
Run Code Online (Sandbox Code Playgroud)

但它不起作用并且我收到错误

无法识别的表达式“$regex”

我怎样才能让它发挥作用?

我原来的查询看起来像这样

db.orders.aggregate([{
$match: {}},
{$lookup: {
    from: "orders",
    let: {
        "customer_details": "$customerDetails"
    },
    pipeline: [
        {
            $match: {
                $expr: {
                        $and: [
                                { $or: [
                                                {
                                                $eq: ["$customerDetails.parentMobile","$$customer_details.parentMobile"]
                                                },
                                                {$eq: ["$customerDetails.studentMobile","$$customer_details.parentMobile"]
                                                },
                                                {$eq: ["$customerDetails.studentMobile","$$customer_details.parentMobile"]
                                                },
                                                {$eq: ["$customerDetails.studentMobile","$$customer_details.studentMobile"]
                                                }
                                            ]
                                        },
                                {$eq: ["$customerDetails.zipCode","$$customer_details.zipCode"]},
                                {$eq: ["$customerDetails.address","$$customer_details.address"]}
                        ]
                    }

            }
        }],
    as: "oldOrder"
}
}])
Run Code Online (Sandbox Code Playgroud)

我想用于regex匹配address

任何帮助将不胜感激。提前致谢。

Ash*_*shh 8

$regex是一个不能在内部使用的查询运算符,$expr因为它只支持聚合管道运算符。

{
  "$expr": { "$gt": ["$age", 10] } ,
  "name": { "$regex": "ab" }
}
Run Code Online (Sandbox Code Playgroud)

如果你有 mongodb 4.2,你可以使用$regexMatch

{ "$expr": {
  "$and": [
    { "$gt": ["$age", 10] },
    {
      "$regexMatch": {
        "input": "$name",
        "regex": "ab", //Your text search here
        "options": "i",
      }
    }
  ]
}}
Run Code Online (Sandbox Code Playgroud)


Moh*_*sry 5

如果你的mongoDB版本是4.2,那么你可以使用$regexMatch

尝试这个

db.collection.find({
  $expr: {
    $and: [
      {
        $gt: [
          "$age",
          10
        ]
      },
      {
        $regexMatch: {
          input: "$name",
          regex: "ab"
        }
      }
    ]
  }
})
Run Code Online (Sandbox Code Playgroud)

检查这个Mongo 游乐场