MongoDB $text Operator

Beginner
6 min read
Updated: Oct 2026
3 examples
Live preview

What Is $text?

$text is a MongoDB query operator for full-text search on fields covered by a text index. It filters documents that match your search terms—it does not transform field values like math operators do.

Remember
$text = search bar for indexed strings

{ $text: { $search: <string> } }

requires → text index on searched fields
terms    → OR by default
phrase   → "\"exact words\""
exclude  → -word

one $text per query
$match + $text → must be first pipeline stage
UsePrefer
Word / phrase search on indexed text$text
Pattern matching (regex)$regex
Relevance score / sort$meta: "textScore"

How to Use $text in MongoDB

Index first, then search. Optionally project and sort by relevance.

  1. Create a text index on the string fields you want to search.
  2. Run find() (or a first-stage $match) with { $text: { $search: "..." } }.
  3. Optional: project { score: { $meta: "textScore" } } and sort by that score.
  4. Optional: use phrases ("\"…\"") or exclusions (-word) in $search.
PieceRequired?Role
Text indexYesMakes fields searchable with $text
$searchYesSearch string (terms, phrase, exclusions)
$language / case / diacritic flagsNoTune stemming and matching rules
$meta: "textScore"NoRelevance for project / sort

Pseudocode

Pseudocode
create text index on title, body

for each document:
    if no text index:
        error
    tokens = tokenize($search)   // stop words dropped
    if document matches any required terms
       and none of the excluded terms:
        keep document
        optionally attach textScore
    else:
        skip

Cheat Sheet

Keep these facts handy while writing text-search queries.

TopicDetail
TypeQuery operator (filter), not a field expression
Syntax{ $text: { $search: "terms" } }
IndexcreateIndex({ title: "text", body: "text" })
Default matchTerms are OR’d; stop words ignored
Phrase$search: "\"exact phrase\""
Exclude$search: "mongodb -sql"
Relevance{ score: { $meta: "textScore" } }

Live Preview

Pick a search string and see which sample articles would match (simple term OR demo—same idea as $text + a text index).

Simulates term matching on three sample articles (not a real MongoDB server).

Result
$search = "mongodb"
matches → 2 documents

[ { _id: 1, title: "MongoDB Text Search" },
  { _id: 3, title: "Aggregation Pipeline" } ]

Worked Walkthrough — Search “mongodb”

Three articles, one text index on title and body. Search term mongodb should hit two of them.

Calculation
Index:
  { title: "text", body: "text" }

Documents:
  1) "MongoDB Text Search" …     → contains mongodb ✓
  2) "Regex Patterns" …          → no mongodb ✗
  3) "Aggregation Pipeline" …
     body mentions MongoDB       → contains mongodb ✓

$query:
  { $text: { $search: "mongodb" } }

Result: documents 1 and 3

MongoDB Examples

Insert sample articles, create a text index, search, then sort by relevance. Run these in mongosh in order.

Example 1 — Sample Data & Index

Insert three short articles, then create one text index on title and body.

mongosh
db.articles.insertMany([
  {
    _id: 1,
    title: "MongoDB Text Search",
    body: "Learn how to search documents with a text index."
  },
  {
    _id: 2,
    title: "Regex Patterns",
    body: "Match strings with regular expressions."
  },
  {
    _id: 3,
    title: "Aggregation Pipeline",
    body: "MongoDB pipelines process documents step by step."
  }
]);

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

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps three documents in articles. Run find() to see them:

mongosh
db.articles.find()

Read the setup like this:

PieceValuePlain English
CollectionarticlesWhere the searchable docs live
Indexed fieldstitle, bodyBoth become searchable via $text
Index type"text"Required before any $text query

How It Works

  1. Insert sample docs. insertMany adds three articles with titles and bodies.
  2. Build the text index. createIndex({ title: "text", body: "text" }) tokenizes those fields.
  3. One text index per collection. That single index can cover multiple fields—ready for the next examples.

Example 3 — Sort by textScore

Same search, but project the relevance score and sort best matches first.

mongosh
db.articles.find(
  { $text: { $search: "mongodb" } },
  { score: { $meta: "textScore" } }
).sort(
  { score: { $meta: "textScore" } }
);

How It Works

  1. Same $text filter. Still searching for mongodb.
  2. Project the score. $meta: "textScore" adds a numeric relevance field.
  3. Sort by that score. Higher scores mean a stronger match for the query.
  4. Scores are relative. Exact numbers can differ by MongoDB version—use them for ordering, not absolute grades.

Edge Cases & Pitfalls

Check these before using $text in production queries.

index

Text index is required

Without a text index, $text fails. Create the index before you search.

once

Only one $text per query

You cannot combine two $text expressions. In aggregation, put $text in the first $match.

vs regex

Not a regex substitute for every case

Need partial character patterns? Use $regex. Need word search + scores? Use $text.

atlas

Atlas Search is a different feature

The Atlas $search stage is richer and separate from the self-managed $text query operator shown here.

Performance Notes

ApproachCostBest for
$text + text indexIndex lookupWord / phrase search on content
$text + textScore sortHigher (score work)Ranked search results
$regex on large textOften slowerSmall sets or pattern needs

Index only the fields you search. Case- or diacritic-sensitive flags can slow queries. Combine other filters carefully—special indexes like geo do not mix with $text.

Key Takeaways

  • Role: full-text search filter on a text index.
  • Setup: create the text index before you query.
  • Syntax: { $text: { $search: "terms" } }.
  • Ranking: sort with $meta: "textScore".

One line: $text answers “which documents match these words?”—after you add a text index.

Frequently Asked Questions

$text performs full-text search on string fields covered by a text index. Use it in find() filters and in a $match stage (must be the first stage) in aggregation.
Yes. 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.
Use { $text: { $search: "terms" } }. Optional fields include $language, $caseSensitive, and $diacriticSensitive.
$text uses a text index for word/phrase search and relevance scoring. $regex matches patterns and is better for small pattern filters. For searchable content at scale, prefer $text.
Project or sort with { $meta: "textScore" }. In find(), add score to the projection and sort by that score descending.
No. A query can include only one $text expression. In aggregation, the $match that uses $text must be the first stage.

Next: $toBool

Convert values to boolean in an aggregation pipeline.

$toBool tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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.

9 people found this page helpful