MongoDB Text Indexes enable fast full-text search on string fields, allowing efficient querying of words and phrases across large text datasets, especially in unstructured or semi-structured data.
Optimizes full-text search on text-based fields.
Supports searching words and phrases within strings.
Improves query performance on large textual datasets.
Useful for unstructured or semi-structured text data.
Create a Text Index in MongoDB
A text index is created using createIndex() on one or more string fields, enabling full-text search across multiple fields and allowing compound text indexes with non-text fields.
Matches documents containing โmongodbโ in text-indexed fields.
Searches across title and tags (text index).
Supports term variations (e.g., โmongodb learningโ).
Returns only documents matched by the text index.
Drop Text Index in MongoDB
Use db.collection.dropIndex() to remove a specific text index from a collection when it is no longer needed or needs to be recreated with different options.
In MongoDB text indexes, field weights control the relevance score of documents by assigning higher importance to matches in specific fields during full-text search.
Weights control how much each field contributes to the text search relevance score.
MongoDB multiplies term matches by field weights to compute the final score.
Default weight is 1 and can be configured during createIndex().
A wildcard text index ($**) indexes all string fields in a collection, enabling full-text search across dynamic or unknown fields in unstructured data.
Indexes every field that contains string data in the collection.
Enables full-text search across unknown or dynamic fields.
Useful for unstructured and ad-hoc search scenarios.
Can be included as part of a compound index.
Example of Wildcard Index in MongoDB
Create the text indexes using a wildcard specifier.
While text indexes are powerful, there are some important limitations to be aware of:
Only One Text Index per Collection: MongoDB allows only one text index per collection.
Limited Use of hint(): The $text query automatically uses the text index and cannot be forced to use another index.
Sorting Limitation: Text search results are typically sorted using textScore, not normal field sorting.
Restrictions in Compound Text Index: Cannot include multi-key or geospatial index fields.
Important Points About MongoDB Text Indexes
MongoDB Text Indexes provide efficient full-text search capabilities with support for weighted fields, multi-field indexing, and easy index management.
Enables fast full-text search on textual data stored in collections.
Created using createIndex() by specifying one or more fields as "text".
Supports field weights to control relevance scoring in search results.
Allows indexing multiple fields and combining text indexes with other index keys.
Can be removed using dropIndex() by specifying the index name.