You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Prisma aggregateRaw中MongoDB正则表达式失效问题求助

解决Prisma aggregateRaw中$regexMatch不支持RegExp对象的问题

问题原因

Prisma的aggregateRaw在传递聚合管道时,无法正确序列化JavaScript的RegExp对象或正则字面量(比如/The Brough/i),导致MongoDB无法识别,抛出$regexMatch needs 'regex' to be of type string or regex错误——尽管这些写法在mongosh中是可行的。

解决方案1:使用字符串正则+options参数

MongoDB的$regexMatch支持传入字符串格式的正则表达式,并通过options参数指定匹配规则(比如"i"表示不区分大小写)。修改你的代码如下:

const result = await prisma.owned_properties.aggregateRaw({
  pipeline: [
    { $match: { organization_id: { $oid: "6290eb7843e100027b70dd78" } } },
    {
      $project: {
        properties: {
          $filter: {
            input: "$properties",
            as: "property",
            cond: {
              $regexMatch: {
                input: "$$property.property_name",
                regex: "The Brou", // 用字符串替代RegExp对象
                options: "i"       // 指定不区分大小写规则
              },
            },
          },
        },
        _id: 0,
      },
    },
  ],
})

解决方案2:用$toLower实现不区分大小写匹配

如果你的需求是精确匹配(仅忽略大小写),而非模糊正则匹配,可以通过将字段和目标字符串都转成小写,再用$eq比较,这种方式在有合适索引的情况下性能更优:

const result = await prisma.owned_properties.aggregateRaw({
  pipeline: [
    { $match: { organization_id: { $oid: "6290eb7843e100027b70dd78" } } },
    {
      $project: {
        properties: {
          $filter: {
            input: "$properties",
            as: "property",
            cond: {
              $eq: [
                { $toLower: "$$property.property_name" },
                "the brou" // 目标字符串同步转成小写
              ]
            },
          },
        },
        _id: 0,
      },
    },
  ],
})

两种方案对比

  • $regexMatch+字符串正则:适合模糊匹配(比如包含某段字符),支持更多正则语法(如通配符、边界匹配)。
  • $toLower+$eq:仅适合精确匹配,性能更优,尤其是当property_name字段有索引时(可结合text索引或自定义小写字段的索引进一步优化)。

内容的提问来源于stack exchange,提问作者1192805

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 19:36:30