$text (Full-Text Search)
Last updated: 2026-10-09
$text (Full-Text Search)
$text runs full-text search on fields covered by a text index. `{ $text: { $search: 'coffee shop' } }`. Create a text index first (db.collection.createIndex({ content: 'text' })); a collection can have at most one. It applies stemming and stop-word removal, supports phrase search with double quotes, and provides a relevance score via $meta: 'textScore'.
| Category | Element & Evaluation |
|---|---|
| MongoDB Version | 2.6+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $text: { $search: <string>, $language: <language>, $caseSensitive: <boolean> } }
⚙️ Parameters
| search | The keywords or phrase to search for. |
|---|---|
| language | Optional; the language for stemming. |
| caseSensitive | Optional; whether the search is case-sensitive. |
Returns:Cursor of matching documents
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $text: full-text search for coffee shop
// Requires a text index first
db.articles.find({ $text: { $search: 'coffee shop' } })
// Sort by relevance (textScore)
db.articles.find(
{ $text: { $search: 'coffee' } },
{ score: { $meta: 'textScore' } }
).sort({ score: { $meta: 'textScore' } })
Output:
// Returns articles matching the coffee/shop stems; the second query ranks by relevance
📌 Notes
- Create a text index first; at most one per collection
- Stemming: searching coffee also matches coffees
- Unlike $regex, $text uses the text index and suits large text
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QWhat must I do before using $text?
ACreate a text index first: db.coll.createIndex({ content: 'text' }).
QWhat is the difference between $text and $regex?
A$text is indexed word-level search with stemming and scoring; $regex is pattern matching, usually a full scan.
QHow do I sort $text results by relevance?
AProject the score with $meta: 'textScore', then sort({ score: { $meta: 'textScore' } }).