Mongodb Case Insensitive query with examples

This tutorial explains about How to search documents with case insensitive queries in MongoDB

We can use the regular expression $regex with options $options =i to do case-insensitive queries.

Students collection contains following records

librarydb > db.students.find({});
[
  { _id: ObjectId("651b9810bf2c71bd2475ced2"), name: "Student2" },
  { _id: ObjectId("651b984abf2c71bd2475ced3"), name: "student 3" },
  { _id: ObjectId("651b986dbf2c71bd2475ced4"), name: "student 1" },
];

Mongodb Search case insensitive documents

Let’s see some search queries Search documents with name = student 3

db.students.find({name:{'$regex' : '^student 3$', '$options' : 'i'}})

Output:

[ { _id: ObjectId("651b984abf2c71bd2475ced3"), name: 'student 3' } ]

Search documents that name contains student

librarydb> db.students.find({name:{'$regex' : 'student', '$options' : 'i'}})
[
  { _id: ObjectId("651b9810bf2c71bd2475ced2"), name: 'Student2' },
  { _id: ObjectId("651b984abf2c71bd2475ced3"), name: 'student 3' },
  { _id: ObjectId("651b986dbf2c71bd2475ced4"), name: 'student 1' }
]

Search documents that name starts with student

librarydb> db.students.find({name:{'$regex' : '^student', '$options' : 'i'}})
[
  { _id: ObjectId("651b9810bf2c71bd2475ced2"), name: 'Student2' },
  { _id: ObjectId("651b984abf2c71bd2475ced3"), name: 'student 3' },
  { _id: ObjectId("651b986dbf2c71bd2475ced4"), name: 'student 1' }
]

Search documents that name end with student 3

librarydb> db.students.find({name:{'$regex' : 'student 3$', '$options' : 'i'}})
[ { _id: ObjectId("651b984abf2c71bd2475ced3"), name: 'student 3' } ]