MongoDB query with case insensitive search?


For case, insensitive search, use regex in find() method. Following is the syntax −

db.demo572.find({"yourFieldName" : { '$regex':/^yourValue$/i}});

To understand the above syntax, let us create a collection with documents −

> db.demo572.insertOne({"CountryName":"US"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e915f0e581e9acd78b427f1")
}
> db.demo572.insertOne({"CountryName":"UK"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e915f17581e9acd78b427f2")
}
> db.demo572.insertOne({"CountryName":"Us"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e915f1b581e9acd78b427f3")
}
> db.demo572.insertOne({"CountryName":"AUS"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e915f20581e9acd78b427f4")
}
> db.demo572.insertOne({"CountryName":"us"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e915f25581e9acd78b427f5")
}

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

> db.demo572.find();

This will produce the following output −

{ "_id" : ObjectId("5e915f0e581e9acd78b427f1"), "CountryName" : "US" }
{ "_id" : ObjectId("5e915f17581e9acd78b427f2"), "CountryName" : "UK" }
{ "_id" : ObjectId("5e915f1b581e9acd78b427f3"), "CountryName" : "Us" }
{ "_id" : ObjectId("5e915f20581e9acd78b427f4"), "CountryName" : "AUS" }
{ "_id" : ObjectId("5e915f25581e9acd78b427f5"), "CountryName" : "us" }

Following is the query for case insensitive search −

> db.demo572.find({"CountryName" : { '$regex':/^US$/i}});

This will produce the following output −

{ "_id" : ObjectId("5e915f0e581e9acd78b427f1"), "CountryName" : "US" }
{ "_id" : ObjectId("5e915f1b581e9acd78b427f3"), "CountryName" : "Us" }
{ "_id" : ObjectId("5e915f25581e9acd78b427f5"), "CountryName" : "us" }

Updated on: 15-May-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements