首页 > 解决方案 > Mongo 文本搜索多个短语 - AND、OR

问题描述

以下返回具有短语“Comp and Comp”和“Low Threat”的所有文档

{ $text: { $search: '"Comp and Comp" "Low Threat"' } }

同样,如何对多个短语进行 OR 文本搜索?

我能得到的最近的是以下内容:

{ $text: { $search: 'Comp and Comp Low Threat' } }

但它没有办法对短语进行分组,它只对单个字符串执行 OR。

标签: mongodbmongodb-queryspring-data-mongodb

解决方案


看起来你不能用文档中的短语来做到这一点:

如果 $search 字符串包含短语和单个术语,则文本搜索将仅匹配包含该短语的文档。

所以基本上这需要任何被标记为短语(带有")的字符串出现在strong中。

您能做的最好的事情是运行一个具有$facet2 个匹配条件的聚合管道,然后分组以消除重复项,如下所示:

db.collection.aggregate([
    {
        $facet: {
            comp: {
                $match: { $text: { $search: '\"Comp and Comp\"' } }
            },
            low: {
                $match: { $text: { $search: '\"Low Threat\"' } }
            }
        }
    },
    {
        $project: {
            merged: {$concatArray: ["$comp", "$low"]}
        }
    },
    {
        $unwind: "$merged"
    },
    {
        $group: {
            _id: "$merged._id",
            root: {$first: "$$ROOT"}
        }
    },
    {
        $replaceRoot: {
            newRoot: "$root"
        }
    },
])

推荐阅读