Case-insensitive search implementation

Hi! How to implement case-insensitive search in MongoDB? (“qWerTy”, “QWRTY”, “qwerty”)
Should I use $regex or something else? Which is the best approach?

Hi @Victor_69915,

One way to do is by using regex as you mentioned like this:

 db.movies.find( { director: /georges Mèliès/i } )

Another way to do it is by creating case insensitive index on the field. This is when you need to do frequent case insensitive queries.

Suppose, you have a collection called movies and you want to perform query on director field irrespective of the case. Then, we will create an index on director field like this:

 db.movies.createIndex( { director: 1}, { collation: { locale: 'en', strength: 2 } } )

Now, you can query like this:

db.movies.find( { director: "georges Mèliès" } ) // does not use index

db.movies.find( { director: "georges Mèliès" } ).collation( { locale: 'en', strength: 2 } )
// uses the index

db.movies.find( { director: "georges Mèliès" } ).collation( { locale: 'en', strength: 1 } )
// does not use the index

Here you can read more about this: