Create an index for text search in MongoDB

To create an index for text search in MongoDB, use the createIndex() method with the "text" index type. This enables full-text search capabilities on string fields using the $text operator.

Syntax

db.collection.createIndex({ fieldName: "text" });
db.collection.find({ $text: { $search: "searchTerm" } });

Sample Data

Let us create a collection with sample documents:

db.demo331.insertMany([
    { "Words": "This is a MySQL" },
    { "Words": "THIS is a MongoDB" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e521c35f8647eb59e562089"),
        ObjectId("5e521c36f8647eb59e56208a")
    ]
}

Display all documents from the collection:

db.demo331.find();
{ "_id": ObjectId("5e521c35f8647eb59e562089"), "Words": "This is a MySQL" }
{ "_id": ObjectId("5e521c36f8647eb59e56208a"), "Words": "THIS is a MongoDB" }

Example: Create Text Index and Search

Create a text index on the Words field:

db.demo331.createIndex({ Words: "text" });
{
    "createdCollectionAutomatically": false,
    "numIndexesBefore": 1,
    "numIndexesAfter": 2,
    "ok": 1
}

Now perform a text search for "MySQL":

db.demo331.find({ $text: { $search: "MySQL" } });
{ "_id": ObjectId("5e521c35f8647eb59e562089"), "Words": "This is a MySQL" }

Key Points

  • Text indexes are case-insensitive and support stemming for multiple languages.
  • Only one text index per collection is allowed (but it can include multiple fields).
  • Text search uses the $text operator with $search for queries.

Conclusion

Text indexes enable powerful full-text search capabilities in MongoDB. Create them using createIndex() with "text" type, then query using the $text operator for efficient text-based searches.

Updated on: 2026-03-15T02:31:35+05:30

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements