MongoDB $regex operator i or I for case insensitive search

MongoDBDatabaseBig Data Analytics

For this, you need to use case insensitive (i). Let us create a collection with documents −

> db.demo759.insertOne({SubjectName:"MySQL"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eb02ba95637cd592b2a4ae7")
}
> db.demo759.insertOne({SubjectName:"MongoDB"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eb02baa5637cd592b2a4ae8")
}
> db.demo759.insertOne({SubjectName:"mongodb"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eb02baf5637cd592b2a4ae9")
}
> db.demo759.insertOne({SubjectName:"MONGODB"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eb02bb85637cd592b2a4aea")
}

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

> db.demo759.find();

This will produce the following output −

{ "_id" : ObjectId("5eb02ba95637cd592b2a4ae7"), "SubjectName" : "MySQL" }
{ "_id" : ObjectId("5eb02baa5637cd592b2a4ae8"), "SubjectName" : "MongoDB" }
{ "_id" : ObjectId("5eb02baf5637cd592b2a4ae9"), "SubjectName" : "mongodb" }
{ "_id" : ObjectId("5eb02bb85637cd592b2a4aea"), "SubjectName" : "MONGODB" }

Following is the query implementing MongoDB regex operator −

> db.demo759.find({"SubjectName":{$regex:/mongodb/i}});

This will produce the following output −

{ "_id" : ObjectId("5eb02baa5637cd592b2a4ae8"), "SubjectName" : "MongoDB" }
{ "_id" : ObjectId("5eb02baf5637cd592b2a4ae9"), "SubjectName" : "mongodb" }
{ "_id" : ObjectId("5eb02bb85637cd592b2a4aea"), "SubjectName" : "MONGODB" }
raja
Published on 01-Jul-2020 10:18:24
Advertisements