Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching in mongo db using mongoose regex vs. text

Can anyone please explain the difference between:

db.collection.find({ $text: { $search: "dog cat" } })

and

Product.find({ "drug": { "$regex": "cols", "$options": "i" } })

When should we go for which one ?

like image 595
Pankaj kumar Panigrahi Avatar asked Mar 05 '16 09:03

Pankaj kumar Panigrahi


1 Answers

Well, both regex and text search ($text) help you to search in text very efficiently. Both have their own advantages and disadvantages, But there are two clear distinctions

regex

  • Regex doesn't take advantage of indexes, unless you are searching in beginning of string using ^ operator.

  • Regex allows you to search partial text. therefore .* and so many other patterns.

  • Regex doesn't support stop or noise words.

$text

text indexes in mongodb are really fast and should be preferred. However, MongoDB does not implement full featured text indexes. One main drawback is, it doesn't support partial match. e.g. if you are searching for cat, it will search only for cat and cats but not bobcat or caterpiller.

Bottom line is if you are looking to implement feature like RDBMS like operator, '$text' will not help you (at least in current implementations of MongoDB, but in future it may change).

like image 197
Saleem Avatar answered Oct 28 '22 17:10

Saleem