MongoDB $text Operator

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
Query / Search

What You’ll Learn

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.

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.

📝 Syntax

First create a text index, then use $text in your query filter:

Step 1 — Create a Text Index

mongosh
db.articles.createIndex({
  title: "text",
  body: "text"
})

Step 2 — Query with $text

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

Minimal Example

mongosh
db.articles.find({
  $text: { $search: "mongodb tutorial" }
})

// In an aggregation pipeline:
db.articles.aggregate([
  {
    $match: {
      $text: { $search: "mongodb tutorial" }
    }
  }
])

$search Modifiers

mongosh
// Multiple terms (OR by default)
{ $search: "mongodb database" }

// Exact phrase (use quotes)
{ $search: "\"aggregation pipeline\"" }

// Exclude a term (prefix with minus)
{ $search: "mongodb -sql" }

// Require all terms (prefix with plus)
{ $search: "+mongodb +tutorial" }

Syntax Rules

  • $search — required; the search string (terms, phrases, exclusions).
  • $language — optional; language for stemming (default: "english").
  • $caseSensitive — optional; case-sensitive matching (default: false).
  • $diacriticSensitive — optional; accent-sensitive matching (default: false).
  • 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)

⚡ Quick Reference

QuestionAnswer
Operator typeQuery operator (full-text search)
Syntax{ $text: { $search: "terms" } }
PrerequisiteText index on searched fields
Common usagefind(), $match in aggregation
Relevance score{ $meta: "textScore" } in projection or sort
Indexes per collectionAt 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

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."
  }
]

Example 1 — Basic find() with $text

Search for documents containing “mongodb”:

mongosh
db.articles.find({
  $text: { $search: "mongodb" }
})

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:

mongosh
db.articles.aggregate([
  {
    $match: {
      $text: { $search: "mongodb aggregation" }
    }
  },
  {
    $project: {
      title: 1,
      body: 1,
      score: { $meta: "textScore" }
    }
  },
  {
    $sort: { score: -1 }
  }
])

How It Works

$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:

mongosh
db.articles.createIndex(
  {
    title: "text",
    body: "text"
  },
  {
    weights: {
      title: 10,
      body: 1
    },
    name: "article_text_index"
  }
)

How It Works

Higher weights boost relevance scores when terms appear in more important fields. This helps search results prioritize titles over body text.

🚀 Use Cases

  • Site search — search blog posts, documentation, or product descriptions by keyword.
  • Knowledge bases — find help articles and FAQs across title and body fields.
  • E-commerce catalogs — search product names and descriptions with relevance ranking.
  • Support tickets — locate customer messages containing specific terms or phrases.
  • Content moderation — filter documents containing flagged words (combined with other query filters).

🧠 How $text Works

1

Create a text index

MongoDB indexes words from the specified string fields into an inverted text index.

Setup
2

Parse the $search string

MongoDB tokenizes terms, handles phrases (quotes), exclusions (-), and language-specific stemming rules.

Parse
3

Look up matching documents

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.

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.

💡 Best Practices

✅ Do

  • Create a text index before running $text queries
  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about $text

Use these points when adding search to your MongoDB application.

5
Core concepts
📝 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.

Continue the Operator Series

Move on to $toBool for type conversion, or explore $meta for relevance scoring.

Next: $toBool →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful