如何将查询转换为使用正则表达式而不是相等

问题描述 投票:1回答:2

我正在使用MongoDB,我有以下记录:

{
    name: "a",
    status: [
        { age: 15, closed: true},
        { age: 38, closed: true},
        { age: 42, closed: false},
    ]
},
{
    name: "b",
    status: [
        { age: 29, closed: true},
        { age: 5, closed: false},
    ]
}

我想检查状态中的前一个对象是否具有例如age = 29。 所以我有这个工作查询:

db.col.find({
    $expr: {
        $eq: [
            29,
            {
                $let: {
                    vars: { beforeLast: { $arrayElemAt: [ "$status", -2 ] } },
                    in: "$$beforeLast.age"
                }
            }
        ]
    }
})

但我现在要检查例如年龄是否包含类似“2”的值。我需要使用正则表达式。无论如何转换该查询以使用正则表达式/而不是$eq运算符? PS:我不想使用聚合,因为我正在使用旧版本。

mongodb mongoose aggregation-framework
2个回答
1
投票

您可以使用$indexOfCP查找字符串字符内的子字符串

db.collection.find({
  "$expr": {
    "$ne": [
      {
        "$indexOfCP": [
          { "$toLower": {
            "$let": {
              "vars": {
                "beforeLast": {
                  "$arrayElemAt": [
                    "$status",
                    -2
                  ]
                }
              },
              "in": "$$beforeLast.age"
            }
          }},
          "2"
        ]
      },
      -1
    ]
  }
})

0
投票

尝试聚合

db.collection.aggregate([
{
 $project:
  {
     last: { $arrayElemAt: [ "$status", -2 ] },
  }
},
{$addFields:{
  ageInString: { $substr: [ "$last.age", 0, 3 ] }
  }},
  {$match:{ageInString:{ $regex: '^2' }}}
])
© www.soinside.com 2019 - 2024. All rights reserved.