klequis / coding-notebook

notes on coding issues
MIT License
0 stars 0 forks source link

MongoDB Case insensitve search #6

Open klequis opened 4 years ago

klequis commented 4 years ago

Goal: find all strings in the 'type' field that start with 'Dog' or 'dog'

Case insensitive searches can be done on fields case insensitive indexes. However, it matches the whole field. For example ...

{ type: 'dog' }

... would work if the value of the field were 'Dog' or 'Dog'. However, if the value of the field is 'Dog is nice' there will be no matches.

To satisfy the 'starts with' condition you can use $regex. In this case you do not need an index. You must include $options: 'i' for case insensitive and 'm to use ahncors.

{ type: { $regex: '^dog', $options: 'im' }}

Solution

{ type: { '$regex': '^dog', '$options': 'im' } }

Ref

Examples

$options => i for case insensitive search

Start with string

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

End with string

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

Contains string

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

Doesn't Contains string

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