How do I make case-insensitive queries on MongoDB?


Use regexp to make case-insensitive queries on MongoDB. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.caseInsensitiveDemo.insertOne({"UserName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f6fec8d10a061296a3c45")
}
> db.caseInsensitiveDemo.insertOne({"UserName":"DAVID"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f6ff28d10a061296a3c46")
}
> db.caseInsensitiveDemo.insertOne({"UserName":"david"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f6ffa8d10a061296a3c47")
}
> db.caseInsensitiveDemo.insertOne({"UserName":"Carol"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f70008d10a061296a3c48")
}
> db.caseInsensitiveDemo.insertOne({"UserName":"Mike"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7f70058d10a061296a3c49")
}
> db.caseInsensitiveDemo.insertOne({"UserName":"Sam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f70098d10a061296a3c4a")
}
> db.caseInsensitiveDemo.insertOne({"UserName":"daVID"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f70138d10a061296a3c4b")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.caseInsensitiveDemo.find().pretty();

The following is the output −

{ "_id" : ObjectId("5c6d7a67f2db199c1278e7ef"), "Name" : "John" }
{ "_id" : ObjectId("5c6d7ad6f2db199c1278e7f0"), "Name" : "JOHN" }
{ "_id" : ObjectId("5c7f6fec8d10a061296a3c45"), "UserName" : "David" }
{ "_id" : ObjectId("5c7f6ff28d10a061296a3c46"), "UserName" : "DAVID" }
{ "_id" : ObjectId("5c7f6ffa8d10a061296a3c47"), "UserName" : "david" }
{ "_id" : ObjectId("5c7f70008d10a061296a3c48"), "UserName" : "Carol" }
{ "_id" : ObjectId("5c7f70058d10a061296a3c49"), "UserName" : "Mike" }
{ "_id" : ObjectId("5c7f70098d10a061296a3c4a"), "UserName" : "Sam" }
{ "_id" : ObjectId("5c7f70138d10a061296a3c4b"), "UserName" : "daVID" }

Here is the query to make case-insensitive queries on MongoDB −

> db.caseInsensitiveDemo.find({UserName: /^david$/i } ).pretty();

The following is the output −

{ "_id" : ObjectId("5c7f6fec8d10a061296a3c45"), "UserName" : "David" }
{ "_id" : ObjectId("5c7f6ff28d10a061296a3c46"), "UserName" : "DAVID" }
{ "_id" : ObjectId("5c7f6ffa8d10a061296a3c47"), "UserName" : "david" }
{ "_id" : ObjectId("5c7f70138d10a061296a3c4b"), "UserName" : "daVID" }

Updated on: 30-Jul-2019

174 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements