Mongo String Queries

Some time ago I learned a useful MongoDB trick while pair programming.

If you tend to query using strings you may already know that MongoDB is by default case-sensitive.

Querying:

db.users.find({name: 'rafael nadal'})

is different from:

db.users.find({name: 'Rafael Nadal'})

Obviously, the best practice is to make sure your data is in a known case, but that might not always be under your control.

Solution

Fortunately, it is possible to use regex in Mongo queries!

regex to da rescue Regular Expressions by xkcd

So in this case we can simply query:

db.users.find({name: /rafael nadal/i})

i is for ignoring case sensitivity.

Rafael Nadal celebration

There are other use cases for regex, like querying partial strings, though keep in mind these queries are relatively slow.

comments powered by Disqus