【问题标题】:$regex within $project mongodb aggregation$project mongodb 聚合中的 $regex
【发布时间】:2025-12-23 22:25:12
【问题描述】:

我有一个users 集合,其中有一个类型为String 的位置字段。我想在文档中传递一个分数字段,显示文档的位置是否类似于文本“Austin”。例如记录的位置是 Austin, Texas,我希望它与 Austin 匹配。我认为可以为此使用 $regex

我写了这个聚合:

$project: {
  score: {
    $cond: 
      if: {
        $regex: {'$location': /Austin/}
      },
      then: 1,
      else: 0
    }
  },
  location: 1,
  firstName: 1,
  lastName: 1
}

但我得到的是:

{
    "name": "MongoError",
    "errmsg": "exception: invalid operator '$regex'",
    "code": 15999,
    "ok": 0
}

【问题讨论】:

  • 抱歉,我编辑了问题。还是一样的错误
  • $location 应该在 'score' 的位置作为 'location'
  • 任何样本数据?我无法猜测 score 是什么样的,以及你想要它的方式。
  • 在 $project 中似乎不支持 $regex,可能需要使用 mapReduce 来构建另一个表。

标签: mongodb mongoose mongodb-query


【解决方案1】:

我知道这是一个老问题,但从 4.2 版开始,您可以使用 $regexMatch

你可以使用这个阶段:

{
  $project: {
    score: {
      $cond: {
        if: {
          $regexMatch: {
            input: "$location",
            regex: "Austin"
          }
        },
        then: 1,
        else: 0
      }
    },
    location: 1,
    firstName: 1,
    lastName: 1
  }
}

例如here

【讨论】: