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
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.
As mentioned by @natac13 and @007_jb mongo shell is an interactive javascript interpreter and hence it is also case-sensitive.
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.
case insensitive (not comparable) (computer science) Treating or interpreting upper- and lowercase letters as being the same.
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/
You can use '$regex':'^win$'
or /^win$/i
(notice no quote on the second one)
Source here : Regex in queries with Mongo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With