mongodb - Mongo 文本搜索多个短语 - AND、OR
问题描述
以下返回具有短语“Comp and Comp”和“Low Threat”的所有文档
{ $text: { $search: '"Comp and Comp" "Low Threat"' } }
同样,如何对多个短语进行 OR 文本搜索?
我能得到的最近的是以下内容:
{ $text: { $search: 'Comp and Comp Low Threat' } }
但它没有办法对短语进行分组,它只对单个字符串执行 OR。
解决方案
看起来你不能用文档中的短语来做到这一点:
如果 $search 字符串包含短语和单个术语,则文本搜索将仅匹配包含该短语的文档。
所以基本上这需要任何被标记为短语(带有"
)的字符串出现在strong中。
您能做的最好的事情是运行一个具有$facet
2 个匹配条件的聚合管道,然后分组以消除重复项,如下所示:
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"
}
},
])
推荐阅读
- ruby - 如何使用存储在相应值中的概率分布从哈希中选择随机键?
- javascript - 如何观察 HTML 类的变化来改变 innerHTML 属性
- python-2.7 - Python中的面积计算
- tensorflow - 使用 Tensorflow 的神经网络成本停滞不前
- split - 使用某个值作为分隔符拆分并移动下一行(python)
- servicestack - 使用带有 ServiceStack.Logging.Serilog 的自定义接收器?
- c++ - 定义带有和不带有 INCLUDED_HEADERNAME_H 的标头有什么区别
- android - 在 Android Studio 中向 TabLayouts 添加图标
- python - 有没有可以用来快速检查库与哪些版本的 Python 兼容的工具?
- python - 散景:连接线图和散点图