Text indexes
A text index makes string fields searchable with $text queries.
In this page:
Syntax
db.collection_name.createIndex({ field1: "text", field2: "text" })
Text indexes
createIndex({ title: "text", body: "text" }) indexes words with stemming and language rules. Weights let some fields count more, and default_language sets the language.
Only one text index is allowed per collection, and queries use $text with $search.
Note:
Use weights to rank title matches above body matches.
Example: Text indexes
test> db.articles.createIndex({ title: "text", body: "text" }, { weights: { title: 10, body: 1 }, name: "articles_text" })
articles_text
test> db.articles.find({ $text: { $search: "index performance" } }).limit(2)
[
{ _id: 7, title: 'Index performance tips', body: '...' },
{ _id: 3, title: 'Schema design', body: 'Good indexes improve performance ...' }
]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Creating two text indexes
- Expecting substring search
- Ignoring language settings
Chapter Summary
- One text index per collection
- Multiple fields allowed
- weights adjust ranking
- $text and $search query it
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: