How to make a case-insensitive query in MongoDB?


For a case-insensitive query, use regex in MongoDB. Let us create a collection with documents −

> db.demo314.insertOne({"Name":"Chris brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e50d742f8647eb59e562056")
}
> db.demo314.insertOne({"Name":"David Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e50d743f8647eb59e562057")
}
> db.demo314.insertOne({"Name":"CHRIS BROWN"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e50d744f8647eb59e562058")
}
> db.demo314.insertOne({"Name":"DAVID MILLER"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e50d747f8647eb59e562059")
}
> db.demo314.insertOne({"Name":"chris brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e50d749f8647eb59e56205a")
}

Display all documents from a collection with the help of find() method −

> db.demo314.find();

This will produce the following output −

{ "_id" : ObjectId("5e50d742f8647eb59e562056"), "Name" : "Chris brown" }
{ "_id" : ObjectId("5e50d743f8647eb59e562057"), "Name" : "David Miller" }
{ "_id" : ObjectId("5e50d744f8647eb59e562058"), "Name" : "CHRIS BROWN" }
{ "_id" : ObjectId("5e50d747f8647eb59e562059"), "Name" : "DAVID MILLER" }
{ "_id" : ObjectId("5e50d749f8647eb59e56205a"), "Name" : "chris brown" }

Following is the query to make a case-insensitive query. This displays “chris brown” name available in every possible case in the document −

> db.demo314.find({"Name":/chris brown/i});

This will produce the following output −

{ "_id" : ObjectId("5e50d742f8647eb59e562056"), "Name" : "Chris brown" }
{ "_id" : ObjectId("5e50d744f8647eb59e562058"), "Name" : "CHRIS BROWN" }
{ "_id" : ObjectId("5e50d749f8647eb59e56205a"), "Name" : "chris brown" }

Updated on: 01-Apr-2020

191 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements