Avoid MongoDB performance issues while using regex

To avoid MongoDB performance issues while using regex, create appropriate text indexes on the fields you'll be searching. Text indexes enable efficient text search operations and significantly improve query performance.

Syntax

db.collection.createIndex({"field1": "text", "field2": "text"});
db.collection.find({"field": {"$regex": "pattern", "$options": "i"}});

Create Text Index

First, create a text index on the fields you'll be searching ?

db.demo531.createIndex({"CountryName": "text", "Name": "text"});
{
    "createdCollectionAutomatically": true,
    "numIndexesBefore": 1,
    "numIndexesAfter": 2,
    "ok": 1
}

Sample Data

db.demo531.insertMany([
    {CountryName: "US", Name: "Chris"},
    {CountryName: "UK", Name: "David"},
    {CountryName: "AUS", Name: "chris"},
    {CountryName: "US", Name: "CHRIS"}
]);

Display all documents to verify the data ?

db.demo531.find();
{ "_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" }

Example: Optimized Regex Query

Use regex with case-insensitive option to find matching documents ?

db.demo531.find({
    CountryName: "US", 
    "Name": {"$regex": "chris", "$options": "i"}
}).limit(4);
{ "_id": ObjectId("5e8b2b60ef4dcbee04fbbbf2"), "CountryName": "US", "Name": "Chris" }
{ "_id": ObjectId("5e8b2badef4dcbee04fbbbf5"), "CountryName": "US", "Name": "CHRIS" }

Key Points

  • Text indexes significantly improve regex query performance on large collections.
  • Use "$options": "i" for case-insensitive regex matching.
  • Combine indexed fields with regex for optimal performance.

Conclusion

Creating text indexes before using regex queries prevents performance bottlenecks. The combination of proper indexing and regex patterns ensures efficient text search operations in MongoDB collections.

Updated on: 2026-03-15T03:24:41+05:30

504 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements