A text index lets MongoDB tokenize string fields and answer $text queries with relevance scoring. It covers whole-word and stemmed matching, not arbitrary substrings, so it fits keyword search but not autocomplete or regex-style prefix search.
Before you start
You should be comfortable with indexes and simple queries. This article uses the MongoDB shell and the Node.js driver.
Step-by-step walkthrough
Step 1: Create one text index with weights
A collection can have only one text index, and it may span several fields. Weights make a match in title count more than one in body, which shapes relevance. Create it once and rebuild on write, since updates cost more.
Step 2: Query with $text and sort by score
Use { $text: { $search: 'index design' } } to match, and project { score: { $meta: 'textScore' } } to sort by relevance. $text matches whole words and stems, so it will not find indexing from index unless stemming applies, and it will not do partial prefixes.
Step 3: Know when to move to a dedicated search engine
Text indexes lack fuzzy matching, ranking control, faceting and language tuning that a search engine provides. For a small keyword search they are enough; for product search or autocomplete, use a dedicated engine and keep MongoDB as the source of truth.
Worked scenario
The weighted index ranks title matches above body matches.
db.articles.createIndex(
{ title: 'text', body: 'text' },
{ weights: { title: 5, body: 1 } }
);
db.articles
.find({ $text: { $search: 'index design' } }, { score: { $meta: 'textScore' } })
.sort({ score: { $meta: 'textScore' } });Walk through the example
The index tokenizes both fields, and the title weight of 5 makes a title hit score higher than the same word in body. The query finds documents containing the stemmed terms, and the sort orders them by the computed score. A document with both terms ranks above one with a single term.
Common mistake
Expecting $text to match substrings, or creating two text indexes, which is not allowed. Another is relying on it for relevance-sensitive search where a dedicated engine is needed.
Verify the behavior
Insert documents with the term in the title and the body and confirm title hits rank higher. Search a partial word and confirm it does not match, then try a stemmed form. Attempt a second text index and read the error.
Interview exercise
Why will $text: { $search: 'ind' } not find a document containing “index”?
Answer and reasoning
A text index tokenizes on word boundaries and stems whole tokens; it does not index every prefix. ind is not a token in the document, so it does not match. For prefix or substring matching you need a different approach, such as a dedicated search engine with n-grams or an autocomplete index.
Continue learning
Compare index selection in Compound indexes and query plans in Explain diagnostics. Read the MongoDB text index documentation and try the MongoDB interview questions.