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
相关产品推荐
相关产品推荐

