Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delimiters for text search in MongoDB

I am trying mongoDB text search in mongoDB server version 2.6.3. When I perform a text search with below query

db.collection.find({"$text" : {"$search" : "a@b"}})  

I am getting as results documents which contain a or b, which means I am getting results for

db.collection.find({"$text" : {"$search" : "a b"}}) 

I am guessing mongo text parser is considering '@' character as delimiter and replacing it with a space. Is there a way we can specify that '@' character shouldn't be considered as a delimiter?

like image 506
Krusheel Munnangi Avatar asked Nov 10 '22 14:11

Krusheel Munnangi


1 Answers

To match on a phrase, as opposed to individual terms, enclose the phrase in escaped double quotes (\"), as in:

"\"a@b\""

So your query would look like:

db.collection.find({"$text" : {"$search" : "\"a@b\""}})

For example:

db.collection.insert([
    {"x": "a@b"},
    {"x": "a b"},
    {"x": "b"},
    {"x": "a"}
]);

db.collection.createIndex({ x: "text"});

The query db.collection.find({"$text" : {"$search" : "\"a@b\""}}) returns

/* 0 */
{
    "_id" : ObjectId("5549ddce180e849972939043"),
    "x" : "a@b"
}
like image 184
chridam Avatar answered Nov 15 '22 04:11

chridam