A text index turns MongoDB into a keyword search engine for your documents: match words across fields, rank the hits by relevance, and weight a title match above a body match. It is not a full search platform, but for "let users search the articles" it is built in, fast, and takes about a minute to set up. Here is how.
Create the index
Mark the searchable fields with the text type. One index can cover several fields:
db.articles.createIndex({ title: "text", body: "text" })
One rule to internalize now: a collection can have only one text index. That is not one per field, it is one total, so you list every field you want searchable inside that single index. The text index docs cover the language and stemming options, which handle plurals and word endings for you.
Search it
Query with $text and $search. By default it matches documents containing any of the words:
db.articles.find({ $text: { $search: "mongodb index" } })
Two modifiers you will use constantly. Wrap a phrase in escaped quotes to require it exactly, and prefix a word with a minus to exclude it:
db.articles.find({ $text: { $search: "\"compound index\" -legacy" } })
// documents with the exact phrase "compound index" but not the word "legacy"
Rank by relevance
By default results come back in natural order, which for search is useless. Ask for the relevance score and sort on it:
db.articles.find(
{ $text: { $search: "mongodb index" } },
{ score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } })
Now the best matches come first, which is the whole point of search.
Weight the fields that matter more
A word in the title should count for more than the same word buried in the body. The weights option sets that:
db.articles.createIndex(
{ title: "text", body: "text" },
{ weights: { title: 10, body: 1 } }
)
A title hit now scores ten times a body hit, so a match in the headline floats to the top. Tune the numbers to your data.
Know where it stops
A text index is keyword search, not a search platform. It handles stemming and stop words and relevance, and that covers a lot. What it does not do is fuzzy matching, synonyms, faceting, or autocomplete. When you need those, the honest answer is that Atlas Search, built on Lucene, is the tool, and a text index is the wrong place to keep pushing. Knowing that line saves you from bending $text into shapes it was never meant to hold.
It is still an index
A text index is real, and it is often the largest index on the collection, because it holds every searchable word. So it earns extra scrutiny in your index budget: worth it if search is a feature, pure cost if that feature got cut and the index stayed. mongoui's Index view shows each index with its storage and how often it is queried, so a heavy text index that nothing searches anymore shows up instead of quietly taxing every write. It runs on your machine, so your content never leaves your network. The general index mechanics are in how to create an index.
