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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 15:27:17