MongoDB聚合管道中$text搜索报错:Unrecognized expression '$text'
问题原因
$text 操作符不能嵌套在 $expr 表达式中使用,你当前把它放在了 $expr 内的 $and 数组里,违反了MongoDB语法规则,因此抛出「Unrecognized expression '$text'」错误。
解决方案
将 $text 条件从 $expr 中移出,直接作为 $match 的顶层条件,和 $expr 用 $and 组合即可。$match 允许同时包含普通查询操作符(如$text)和聚合表达式(如$expr)。
修改后的代码如下:
model.findSearchedItemsByConditions = async (conditions = {}, text) => { try { return await ItemModel.aggregate([ { $match: conditions }, { $lookup: { from: 'datas', let: { 'itemId': '$_id' }, pipeline: [ { $match: { $and: [ { $expr: { $eq: ["$parentId", "$$itemId"] } }, { $text: { $search: text } } ] } } ], as: "data" } }, { $sort: { createdAt: -1 } } ]); } catch (error) { console.log({ error }); } }
额外注意事项
- 确认已在
datas集合的目标字段上创建文本索引,比如要搜索content字段,索引创建语句为:db.datas.createIndex({ content: "text" }) - 单个MongoDB集合只能创建一个文本索引,但该索引可包含多个字段
内容的提问来源于stack exchange,提问作者user3384985
相关产品推荐
相关产品推荐

