How to match exact phrase with dynamic string in text index Mongodb?

喜欢而已 提交于 2020-02-16 07:24:10

问题


I have this query

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

Now my text search is dynamic

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

But it does not give me expected output with nodejs. So How can I parse the backslash here?


回答1:


Your query is incorrect. You need to change the query

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

to

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

Since, there is an extra double quote (") in the beginning after the first backquote. Doing that will fix your query.

Simple illustration:

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

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


来源:https://stackoverflow.com/questions/59988073/how-to-match-exact-phrase-with-dynamic-string-in-text-index-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!