The $text operator performs full-text search on string fields covered by a text index. Use it in find() queries and $match stages to search articles, products, comments, and other text-heavy data.
01
Full-Text Search
Search indexed strings.
02
Text Index
Required setup step.
03
Syntax
$search and options.
04
find() & $match
Query and pipeline.
05
Relevance Score
Sort with textScore.
06
vs $regex
When to use each.
Fundamentals
Definition and Usage
In MongoDB, the $text operator is a query operator that searches for words and phrases in text-indexed fields. Unlike math operators such as $abs or $tanh, $text does not transform field values — it filters documents that match your search terms.
Before you can search, create a text index on the fields you want to query. Then pass your search string to $search. MongoDB tokenizes the text, applies language-specific rules (stemming, stop words), and returns matching documents.
💡
Beginner Tip
Think of $text as MongoDB’s built-in search bar. You index the content once, then query with natural language terms instead of writing complex regex patterns.
Foundation
📝 Syntax
First create a text index, then use $text in your query filter:
Text index required — one text index per collection (can cover multiple fields).
One $text per query — you cannot use two $text operators in the same query.
💡 $text vs $regex
$text — full-text search with a text index; relevance scoring; best for searchable content
$regex — pattern matching; flexible but slower on large collections without careful indexing
Index rule — $text requires a text index; $regex may or may not use indexes depending on the pattern
Relevance — pair $text with $meta: "textScore" to sort by match quality (see $meta)
Cheat Sheet
⚡ Quick Reference
Question
Answer
Operator type
Query operator (full-text search)
Syntax
{ $text: { $search: "terms" } }
Prerequisite
Text index on searched fields
Common usage
find(), $match in aggregation
Relevance score
{ $meta: "textScore" } in projection or sort
Indexes per collection
At most one text index
Basic
{
$text: {
$search: "mongo"
}
}
Simple search
Phrase
{
$text: {
$search: "\"text index\""
}
}
Exact phrase
Exclude
{
$text: {
$search: "mongo -sql"
}
}
Exclude term
Score
{
score: {
$meta: "textScore"
}
}
Relevance field
Hands-On
Examples Gallery
Set up a text index on an articles collection, run searches with find() and aggregation, and rank results by relevance.
📚 Article Search Setup
Create a text index, add sample articles, and run your first full-text search.
Step 0 — Create a Text Index
Index the title and body fields before running any $text query:
mongosh
db.articles.createIndex({
title: "text",
body: "text"
})
// Verify the index
db.articles.getIndexes()
How It Works
MongoDB builds an inverted index of words from the indexed fields. Each collection supports at most one text index, but that index can include multiple string fields.
Sample Input Documents
Suppose you have these documents in articles:
mongosh
[
{
"_id": 1,
"title": "MongoDB Aggregation Tutorial",
"body": "Learn pipelines, $match, and $project stages."
},
{
"_id": 2,
"title": "Introduction to Databases",
"body": "A beginner guide covering SQL and NoSQL options."
},
{
"_id": 3,
"title": "Advanced MongoDB Tips",
"body": "Indexing, aggregation, and performance tuning for MongoDB."
},
{
"_id": 4,
"title": "SQL vs NoSQL",
"body": "Compare relational and document database models."
}
]
// Matches documents 1 and 3 (title or body contains "mongodb")
{ "_id": 1, "title": "MongoDB Aggregation Tutorial", ... }
{ "_id": 3, "title": "Advanced MongoDB Tips", ... }
How It Works
MongoDB tokenizes the search string, looks up matching terms in the text index, and returns documents that contain those terms. Matching is case-insensitive by default.
📈 Advanced Search Patterns
Use aggregation pipelines, phrase search, exclusions, and relevance scoring.
Example 2 — $text in an Aggregation Pipeline
Search with $match, project a relevance score, and sort by best match:
$match filters to matching documents. $meta: "textScore" adds a relevance score. Higher scores mean stronger matches. See the $meta operator tutorial for more on textScore.
Example 3 — Phrase Search with Quotes
Search for an exact phrase by wrapping it in double quotes inside $search:
mongosh
db.articles.find({
$text: { $search: "\"aggregation pipeline\"" }
})
// Matches documents where "aggregation" and "pipeline"
// appear together as a phrase
How It Works
Without quotes, MongoDB treats space-separated terms as an OR search. Quotes require the words to appear adjacent and in order.
Example 4 — Exclude Terms with a Minus Sign
Find MongoDB articles but exclude SQL-related content:
mongosh
db.articles.find({
$text: { $search: "mongodb -sql" }
})
// Returns MongoDB matches that do NOT contain "sql"
How It Works
Prefix a term with - to exclude documents containing that word. Combine with other terms to narrow results.
Example 5 — Combine $text with Other Filters
Full-text search works alongside regular field filters:
mongosh
db.articles.find({
$text: { $search: "database" },
category: "tutorial",
published: true
})
// Text search + exact match on category and published
How It Works
MongoDB applies all conditions with AND logic. The document must match the text search and satisfy the other field filters.
Bonus — Weighted Text Index Fields
Give title matches more importance than body matches when creating the index:
The text index returns document IDs that contain the search terms.
Match
=
🔍
Ranked search results
Use $meta: "textScore" to sort by relevance and show the best matches first.
Wrap Up
Conclusion
The $text operator brings full-text search to MongoDB. Create a text index once, then query with natural language terms in find() or $match. Pair it with $meta: "textScore" to rank results by relevance.
For pattern-based filters on small fields, $regex may suffice. For searchable content at scale, $text with a proper text index is the better choice. Next in the series: $toBool.
Use field weights to prioritize title over body text
Sort by textScore when showing search results to users
Use quoted phrases for exact multi-word searches
Combine $text with other filters to narrow results
❌ Don’t
Run $text without a text index (it will error)
Use two $text operators in the same query
Expect $text to work inside $project like math operators
Rely on $regex for large-scale content search
Forget that each collection supports only one text index
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about $text
Use these points when adding search to your MongoDB application.
5
Core concepts
🔍01
Full-Text Search
Query indexed strings.
Purpose
📝02
Text Index First
Required setup.
Prerequisite
🔢03
$search String
Terms, phrases, -exclude.
Syntax
🛠04
find() / $match
Query operator.
Usage
⚠05
textScore
Sort by relevance.
Ranking
❓ Frequently Asked Questions
$text performs full-text search on string fields that are covered by a text index. It matches documents containing the search terms and is used in find() queries and $match stages in aggregation pipelines.
Yes. You must create a text index on the fields you want to search. Without a text index, MongoDB returns an error when you run a $text query.
The syntax is { $text: { $search: "search terms" } }. Optional fields include $language, $caseSensitive, and $diacriticSensitive.
$text uses a text index for full-text search and relevance scoring. $regex matches patterns with regular expressions and is better for small, pattern-based filters. For large searchable content, $text is usually the better choice.
Add { score: { $meta: "textScore" } } to your projection, then sort by score descending. The textScore metadata is only available when the query includes $text.