MongoDB query for specific case insensitive search


Let us first create a collection with documents −

> db.demo186.insertOne({"UserEmailId":"JOHN@GMAIL.COM","UserName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e399d769e4f06af55199808")
}
> db.demo186.insertOne({"UserEmailId":"chris@gmail.com","UserName":"chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e399d879e4f06af55199809")
}
> db.demo186.insertOne({"UserEmailId":"DAVID@GMAIL.COM","UserName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e399d979e4f06af5519980a")
}

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

> db.demo186.find();

This will produce the following output −

{ "_id" : ObjectId("5e399d769e4f06af55199808"), "UserEmailId" : "JOHN@GMAIL.COM", "UserName" : "John" }
{ "_id" : ObjectId("5e399d879e4f06af55199809"), "UserEmailId" : "chris@gmail.com", "UserName" : "chris" }
{ "_id" : ObjectId("5e399d979e4f06af5519980a"), "UserEmailId" : "DAVID@GMAIL.COM", "UserName" : "David" }

Following is the query for case insensitive search −

> var userMailId = [ /john@gmail.com/i, /david@gmail.com/i ]
> db.demo186.find({
...   '$or': [
...      { 'UserEmailId': { '$in': userMailId} },
...      { 'UserName': 'John' }
...   ]
...})

This will produce the following output −

{ "_id" : ObjectId("5e399d769e4f06af55199808"), "UserEmailId" : "JOHN@GMAIL.COM", "UserName" : "John" }
{ "_id" : ObjectId("5e399d979e4f06af5519980a"), "UserEmailId" : "DAVID@GMAIL.COM", "UserName" : "David" }

Updated on: 27-Mar-2020

194 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements