首页 > 解决方案 > 如何在文本索引Mongodb中将精确短语与动态字符串匹配?

问题描述

我有这个查询

db.words.find({ "$text": { "$search": "\"cake sale\"" } }) // gives expected answer in robo3T

现在我的text搜索是动态的

const text = "cake sale"
db.words.find({ "$text": { "$search": `\\"${text}\\"` } })

但它并没有给我预期的 nodejs 输出。那么如何在这里解析反斜杠呢?

标签: node.jsmongodbmongodb-query

解决方案


您的查询不正确。您需要更改查询

db.words.find({ "$text": { "$search": `"\"${text}\"` } })

db.words.find({ "$text": { "$search": `\"${text}\"` } })

因为,在第一个反引号之后的开头有一个额外的双引号 ( ")。这样做将修复您的查询。

简单说明:

console.log("\"cake sale\"");

var text = "cake sale";
console.log(`\"${text}\"`);
// both the console.log gives same result


推荐阅读