MongoDB query for specific case insensitive search

MongoDBDatabaseBig Data Analytics

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" }
raja
Published on 27-Mar-2020 08:10:05
Advertisements