Indexing large text field to make query faster in MongoDB

To index large text fields for faster query performance, create an index on the text field using createIndex() and then use $regex for pattern matching queries. The index enables MongoDB to efficiently search through large text data.

Syntax

db.collection.createIndex({"fieldName": 1});
db.collection.find({"fieldName": {$regex: /pattern/}});

Create Sample Data

First, create an index on the Name field for optimized text searches ?

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

Insert sample documents with text data ?

db.demo46.insertMany([
    {"Name": "John Smith"},
    {"Name": "John Doe"},
    {"Name": "Chris Brown"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e267004cfb11e5c34d898ed"),
        ObjectId("5e267009cfb11e5c34d898ee"),
        ObjectId("5e267011cfb11e5c34d898ef")
    ]
}

View Sample Data

db.demo46.find();
{ "_id": ObjectId("5e267004cfb11e5c34d898ed"), "Name": "John Smith" }
{ "_id": ObjectId("5e267009cfb11e5c34d898ee"), "Name": "John Doe" }
{ "_id": ObjectId("5e267011cfb11e5c34d898ef"), "Name": "Chris Brown" }

Example: Pattern Matching with Indexed Field

Search for names starting with "John" using the indexed field ?

db.demo46.find({"Name": {$regex: /^John/}});
{ "_id": ObjectId("5e267009cfb11e5c34d898ee"), "Name": "John Doe" }
{ "_id": ObjectId("5e267004cfb11e5c34d898ed"), "Name": "John Smith" }

Key Points

  • Index first: Always create an index before querying large text fields for optimal performance.
  • Prefix queries: Use ^ in regex patterns (like /^John/) to leverage index efficiency.
  • Performance boost: Indexed text fields provide significantly faster query execution on large datasets.

Conclusion

Indexing text fields with createIndex() combined with $regex pattern matching provides efficient text search capabilities. This approach dramatically improves query performance on large text datasets.

Updated on: 2026-03-15T02:49:03+05:30

255 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements