Avoid MongoDB performance issues while using regex


To avoid performance issues in MongoDB, use the concept of index. Let us create a collection with documents −

> db.demo531.createIndex({"CountryName":"text","Name":"text"});{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
> db.demo531.insertOne({CountryName:"US","Name":"Chris"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b2b60ef4dcbee04fbbbf2")
}
> db.demo531.insertOne({CountryName:"UK","Name":"David"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b2b6cef4dcbee04fbbbf3")
}
> db.demo531.insertOne({CountryName:"AUS","Name":"chris"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b2b74ef4dcbee04fbbbf4")
}
> db.demo531.insertOne({CountryName:"US","Name":"CHRIS"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b2badef4dcbee04fbbbf5")
}

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

> db.demo531.find();

This will produce the following output −

{ "_id" : ObjectId("5e8b2b60ef4dcbee04fbbbf2"), "CountryName" : "US", "Name" : "Chris" }
{ "_id" : ObjectId("5e8b2b6cef4dcbee04fbbbf3"), "CountryName" : "UK", "Name" : "David" }
{ "_id" : ObjectId("5e8b2b74ef4dcbee04fbbbf4"), "CountryName" : "AUS", "Name" : "chris" }
{ "_id" : ObjectId("5e8b2badef4dcbee04fbbbf5"), "CountryName" : "US", "Name" : "CHRIS" }

Following is the query to use regex −

> db.demo531.find({CountryName: "US", "Name": { "$regex": "chris", "$options": "i" }}).limit(4);

This will produce the following output −

{ "_id" : ObjectId("5e8b2b60ef4dcbee04fbbbf2"), "CountryName" : "US", "Name" : "Chris" }
{ "_id" : ObjectId("5e8b2badef4dcbee04fbbbf5"), "CountryName" : "US", "Name" : "CHRIS" }

Updated on: 13-May-2020

360 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements