Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive search in Mongo

I am using a case insensitive search in Mongo, something similar to https://stackoverflow.com/q/5500823/1028488.

ie I am using a regex with options i. But I am having trouble restricting the regex to just that word, it performs more like a 'Like' in SQL

eg: if I use query like {"SearchWord" : { '$regex' : 'win', $options: '-i' }}, it shows me results for win, window & winter. How do i restrict it to jsut show win?

I tried /^win$/ but it's saying invalid JSON... Please suggest away.

Thanks in advance

like image 272
Praneeta Avatar asked Nov 23 '11 16:11

Praneeta


People also ask

How do I do a case-insensitive search in MongoDB?

The aggregation framework was introduced in mongodb 2.2 . You can use the string operator "$strcasecmp" to make a case-insensitive comparison between strings. It's more recommended and easier than using regex.

Is MongoDB data case-sensitive?

As mentioned by @natac13 and @007_jb mongo shell is an interactive javascript interpreter and hence it is also case-sensitive.

How do I search in MongoDB?

Use the $text query operator to perform text searches on a collection with a text index. $text will tokenize the search string using whitespace and most punctuation as delimiters, and perform a logical OR of all such tokens in the search string.

What does case-insensitive mean?

case insensitive (not comparable) (computer science) Treating or interpreting upper- and lowercase letters as being the same.


2 Answers

You can Use $options => i for case insensitive search. Giving some possible examples required for string match.

Exact case insensitive string

db.collection.find({name:{'$regex' : '^string$', '$options' : 'i'}}) 

Contains string

db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}}) 

Start with string

db.collection.find({name:{'$regex' : '^string', '$options' : 'i'}}) 

End with string

db.collection.find({name:{'$regex' : 'string$', '$options' : 'i'}}) 

Doesn't Contains string

db.collection.find({name:{'$regex' : '^((?!string).)*$', '$options' : 'i'}}) 

Keep this as a bookmark, and a reference for any other alterations you may need. http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

like image 59
Somnath Muluk Avatar answered Oct 15 '22 05:10

Somnath Muluk


You can use '$regex':'^win$' or /^win$/i (notice no quote on the second one)

Source here : Regex in queries with Mongo

like image 35
Aurélien B Avatar answered Oct 15 '22 06:10

Aurélien B