Text search basics
A text index enables $text queries that search words in string fields with stemming and scoring.
In this page:
Syntax
db.collection_name.createIndex({ field: "text" })
db.collection_name.find({ $text: { $search: "words" } })
Text search basics
Create one text index per collection over one or more string fields, then query with { $text: { $search: "words" } }. Results can be sorted by relevance with the textScore meta projection.
Text search handles word stemming and stop words but not partial words; Atlas Search offers richer options.
Note:
A collection can have only one text index.
Example: Text search basics
test> db.articles.createIndex({ title: "text", body: "text" })
title_text_body_text
test> db.articles.insertMany([
... { _id: 1, title: "Learning MongoDB", body: "Documents and collections" },
... { _id: 2, title: "Cooking pasta", body: "Boil water" }
... ])
test> db.articles.find({ $text: { $search: "mongodb documents" } }, { title: 1, score: { $meta: "textScore" } })
[ { _id: 1, title: 'Learning MongoDB', score: 1.3333333333333333 } ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Querying $text without a text index
- Expecting partial word matches
- Creating several text indexes on one collection
Chapter Summary
- Create a text index first
- Query with $text and $search
- Sort by textScore for relevance
- Only one text index per collection
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: