1

What is the best way to implement case-insensitive queries in MongoDB?

For example, A database has a collection of contacts with a first name field. One document has 'Adam' in the first name field, another has 'adam'. What is the best way to query for documents with the first name = 'adam', regardless of the case?

2 Answers2

9

Regex is your best bet:

db.collection.find({name: /^adam$/i})

If you're pre-3.2 then you'll need to use the $regex operator:

db.collection.find({name: { $regex: /^adam$/, $options: 'i'}})
BanksySan
  • 27,362
  • 33
  • 117
  • 216
0
db.contacts.find({firstName: /^adam$/i })
ggallo
  • 348
  • 1
  • 11