$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'.

CategoryElement & Evaluation
MongoDB Version2.6+
Example Languagemongosh (Shell)

📝 Syntax

{ $text: { $search: <string>, $language: <language>, $caseSensitive: <boolean> } }

⚙️ Parameters

searchThe keywords or phrase to search for.
languageOptional; the language for stemming.
caseSensitiveOptional; 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

📚 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' } }).
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏