.NET driver - trouble encoding the search string for exact phrases

I am attempting to do text searches with exact phrases via the .NET driver.

The guidance in the MongoDB documentation is to encode a search string in escaped quotes to force searching for an exact phrase, e.g. db.articles.find( { $text: { $search: "\"coffee shop\"" } } ).

In the .NET driver, I create my search string like this: $"\""coffee shop\""", which creates the correct search string. (Note this syntax is an interpolated string, although any method will work just fine).

However, I get no search results when I am expecting them, and confirm them via the mongo console. When I analyse the final search string passed to MongoDB from my code, I see that it has multiple backslashes, e.g. "$text" : { "$search" : "\\\"coffee shop\\\"" } }. I suspect that this is why I get no results.

Has anyone else experienced this or know why this might be happening, and how to fix it?

Hi @Greg_May, and welcome to the forum!

Assuming that you would like to substitute the value i.e. “coffee shop” from a variable, you could do as the following example using interpolated string:

var mySearch = "coffee shop";
var query = new BsonDocument ( "$text", new BsonDocument(
                "$search", $"\"{mySearch}\""