Dark Knight
Dark Knight

Reputation: 1093

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

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?

Upvotes: 1

Views: 541

Answers (1)

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

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

Upvotes: 2

Related Questions