MongoDB $search Stage

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

What Is $search?

$search is an Atlas Search aggregation stage for full-text, relevance-ranked queries—product search, article lookup, and typo-tolerant matching—not plain field equality.

Remember
$search = Atlas full-text search in a pipeline

Requires: MongoDB Atlas + a Search index

{ $search: {
    index: "default",          // optional if named "default"
    text: {
      query: "mongodb",
      path: "title"
    }
  }
}

must be the FIRST stage
score → { $meta: "searchScore" }
$match + $regex → scan, no ranking
$search → indexed, ranked, fuzzy-capable
UsePrefer
User search box / relevance$search (Atlas)
Exact filters / ranges$match
Legacy text index (non-Atlas)$text

How to Use $search in MongoDB

Index first, search first in the pipeline, then shape results.

  1. Use an Atlas cluster and create a Search index on the fields you query.
  2. Put $search as the first stage (required).
  3. Choose an operator—start with text (query + path).
  4. Follow with $project (include searchScore), then $limit.
PieceRequired?Role
Search indexYesDefines searchable fields
index nameNo*Defaults to "default"
Operator (text, …)YesHow to match documents
$meta: "searchScore"NoExpose relevance in output

*If your index is not named default, you must pass index.

Pseudocode

Pseudocode
// Prerequisites
cluster = Atlas
index = Search index on collection (e.g. "default")

// Pipeline
assert $search is stage #1
hits = AtlasSearch.query(index, operator)
for each hit in relevance order:
  attach searchScore metadata
  emit document

// Next stages (optional)
project fields + score
limit top N

Cheat Sheet

Keep these facts handy while building search queries.

TopicDetail
PlatformMongoDB Atlas Search
PositionMust be first stage
Basic texttext: { query, path }
Score{ $meta: "searchScore" }
Typosfuzzy: { maxEdits: 1 }
Missing indexOften empty results
vs $matchRanked search vs exact filters

Live Preview

Teaching model of title search + a simple relevance score (not Lucene—shows the idea of ranked hits before Atlas).

Simulates ranked title matches (real Atlas Search uses a Search index).

Result
Loading…

Worked Walkthrough — Search Titles for “mongodb”

Articles are indexed on title. Goal: find titles about MongoDB, with scores, top 3.

Calculation
1. Atlas Search index on title (and body)
2. $search text query "mongodb" on path "title"
3. Matching docs get a searchScore
4. $project keeps title + score
5. $limit 3 keeps the strongest hits

Example ranking (illustrative scores):
  Intro to MongoDB     score ~3.2
  Node.js + MongoDB    score ~2.8
  Aggregation Basics   score ~1.1  (weaker / no strong title hit)

MongoDB Examples

Run on an Atlas cluster after creating a Search index. Sample scores below are illustrative—your searchScore values will differ.

Example 1 — Sample Data & Index

Insert articles, then create a simple Search index named default on title and body.

mongosh
db.articles.drop();
db.articles.insertMany([
  { title: "Intro to MongoDB", body: "Learn documents, collections, and CRUD." },
  { title: "Aggregation Basics", body: "Build pipelines with $match and $group." },
  { title: "Node.js + MongoDB", body: "Connect Express apps to Atlas." },
  { title: "Indexing Strategies", body: "Speed up queries with the right indexes." },
  { title: "REST API Design", body: "Design clear JSON APIs for clients." }
]);

// Atlas Search index (mongosh on Atlas / supported drivers)
db.articles.createSearchIndex(
  "default",
  {
    mappings: {
      dynamic: false,
      fields: {
        title: { type: "string" },
        body: { type: "string" }
      }
    }
  }
);

How the Data Is Stored in MongoDB

Documents live in articles. The Search index is separate from a normal B-tree index—Atlas builds it for $search.

mongosh
db.articles.find({}, { title: 1, _id: 0 })
db.articles.getSearchIndexes()

Read the important pieces like this:

PieceExamplePlain English
title"Intro to MongoDB"Primary search field
bodyArticle textAlso searchable
Index namedefaultWhat $search uses

How It Works

  1. Insert documents. Normal collection data.
  2. createSearchIndex. Tells Atlas which string fields to analyze.
  3. Wait for READY. Queries before the index is ready may return nothing.

Example 2 — Text Search + Score

Goal: find articles about MongoDB, show relevance, keep top 3.

mongosh
db.articles.aggregate([
  {
    $search: {
      index: "default",
      text: {
        query: "mongodb",
        path: "title"
      }
    }
  },
  {
    $project: {
      _id: 0,
      title: 1,
      score: { $meta: "searchScore" }
    }
  },
  { $limit: 3 }
]);

How It Works

  1. $search first. Required position; uses the default index.
  2. text operator. Looks for mongodb in title.
  3. searchScore. $meta exposes ranking for display or further sorting.
  4. $limit. Caps how many hits you return to the client.

Example 3 — Fuzzy Search

Goal: tolerate a typo like mongdb (missing “o”) using fuzzy.maxEdits.

mongosh
db.articles.aggregate([
  {
    $search: {
      index: "default",
      text: {
        query: "mongdb",
        path: "title",
        fuzzy: { maxEdits: 1 }
      }
    }
  },
  {
    $project: {
      _id: 0,
      title: 1,
      score: { $meta: "searchScore" }
    }
  },
  { $limit: 3 }
]);

How It Works

  1. Typo in the query. Exact text without fuzzy may miss.
  2. maxEdits: 1. Allows one character change (insert/delete/substitute).
  3. Still ranked. Closer matches tend to score higher.
  4. Keep edits small. Larger fuzziness can return noisy hits.

Edge Cases & Pitfalls

Check these before shipping Atlas Search in production.

atlas

Not on plain Community MongoDB

$search needs Atlas Search. For self-hosted text search, look at legacy $text instead.

order

$search must be first

Putting $match or $project before $search fails. Filter after search, or use Search operators / compound queries.

index

Wrong index → empty results

A misspelled index name or a field not mapped as string often returns [] without a helpful error. Verify with getSearchIndexes().

vs

Do not replace all $match with $search

Use $search for text relevance. Keep $match for exact IDs, ranges, and boolean filters after (or via compound).

Performance Notes

ApproachCostBest for
$search + $limitIndex lookup + top hitsSearch boxes / APIs
$match + $regexCollection/index scanSimple patterns, no ranking
Narrow mappingsSmaller Search indexFaster builds & queries

Index only the fields users search. Always $limit results. Prefer $search over regex for large text corpora on Atlas.

Key Takeaways

  • Role: Atlas full-text search in aggregation.
  • First stage + Search index required.
  • Score: { $meta: "searchScore" }.
  • Fuzzy helps with small typos.

One line: $search answers “find relevant documents by text on Atlas.”

Frequently Asked Questions

$search runs full-text, relevance-ranked queries inside an aggregation pipeline using Atlas Search. It matches indexed fields by terms (and options like fuzzy), not just exact equality like a simple $match.
Yes. $search is Atlas Search (Lucene-based). It is not available on a plain self-hosted MongoDB Community server without Atlas Search.
An Atlas Search index on the collection (Atlas UI or createSearchIndex). Queries use that index—often named "default". Wrong or missing index names return empty results, not always a loud error.
First. $search (and $searchMeta) must be the first stage in the pipeline that contains them. Follow with $project, $limit, $sort, or $facet as needed.
After $search, project score: { $meta: "searchScore" }. Higher scores mean stronger matches. Results are typically already ordered by relevance.
$regex scans documents and has no built-in ranking. $search uses a search index, supports fuzzy matching and compound logic, and exposes searchScore—better for user-facing search boxes.

Next: $set

Add or update fields in the pipeline (alias of $addFields).

$set tutorial →

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