MongoDB $meta Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Text Search

What You’ll Learn

The $meta operator returns metadata about a document in a projection or sort. The most common use is textScore — the relevance score from a $text full-text search query.

01

Metadata

Extra query info.

02

textScore

Search relevance.

03

$text Required

Full-text search.

04

$project

Include score field.

05

Sort by Score

Best matches first.

06

Text Index

Prerequisite setup.

Definition and Usage

In MongoDB, the $meta operator exposes metadata that the server computes during a query. For full-text search, when you use $text: { $search: "..." }, MongoDB ranks matching documents. { $meta: "textScore" } lets you read that relevance score in the result set and sort by it.

Higher textScore values generally mean a better match. This is useful for search UIs, article listings, and any feature where users expect the most relevant results first.

💡
Beginner Tip

$meta is a projection and sort operator, not a general math expression like $add. You use it in the projection document of find(), inside $project / $addFields, and in $sort stages.

📝 Syntax

Use $meta in projections and sorts with the metadata keyword "textScore":

In a projection (find() or $project)

mongosh
{ <fieldName>: { $meta: "textScore" } }

In a sort (.sort() or $sort)

mongosh
{ <fieldName>: { $meta: "textScore" } }

Prerequisites for textScore

mongosh
// 1. Create a text index
db.articles.createIndex({
  title: "text",
  body: "text"
})

// 2. Query with $text
{ $text: { $search: "mongodb tutorial" } }

// 3. Project the score
{ score: { $meta: "textScore" } }

Syntax Rules

  • textScore — the primary metadata type for full-text search relevance.
  • Requires $text — the query must include a $text operator.
  • Requires text index — searched fields must have a text index.
  • Use in projection to expose the score as a field (e.g. score or relevance).
  • Use the same field name in $sort to order by relevance (typically -1 for best first).

⚠️ textScore Only Works With $text Queries

$meta: "textScore" returns a score only when the query includes $text. Without it, the metadata field will not contain a meaningful relevance value. Atlas Search and other search products use different APIs.

⚡ Quick Reference

QuestionAnswer
Operator typeProjection / sort metadata operator
Common metadata"textScore"
Projection syntax{ score: { $meta: "textScore" } }
RequiresText index + $text in query
Common stages$match + $project + $sort
$project
{
  title: 1,
  score: {
    $meta: "textScore"
  }
}

Add relevance field

$sort
{
  $sort: {
    score: {
      $meta: "textScore"
    }
  }
}

Sort by relevance

find()
db.articles.find(
  { $text: {
    $search: "mongo"
  }},
  { score: {
    $meta: "textScore"
  }}
)

Works in find too

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

Text search filter

Examples Gallery

Walk through an articles collection with a text index, run a $text search, and retrieve relevance scores with $meta.

📚 Article Search

Set up full-text search on an articles collection and rank results by relevance.

Step 0 — Create a Text Index

Before using textScore, create a text index on the fields you want to search:

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

Sample Input Documents

Suppose you have these documents in articles:

mongosh
[
  {
    "_id": ObjectId("609c26812e9274a86871bc6a"),
    "title": "MongoDB Aggregation Tutorial",
    "body": "Learn pipelines, $match, and $project stages."
  },
  {
    "_id": ObjectId("609c26812e9274a86871bc6b"),
    "title": "Introduction to Databases",
    "body": "A beginner guide covering SQL and NoSQL options."
  },
  {
    "_id": ObjectId("609c26812e9274a86871bc6c"),
    "title": "Advanced MongoDB Tips",
    "body": "Indexing, aggregation, and performance tuning for MongoDB."
  }
]

Example 1 — $meta in an Aggregation Pipeline

Search for “mongodb aggregation”, project the text score, and sort by relevance:

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

How It Works

  • $match with $text filters to documents containing the search terms.
  • $project adds a score field via { $meta: "textScore" }.
  • $sort orders results so the best matches appear first.

📈 find() and Filtering

Use $meta outside aggregation and combine scores with other logic.

Example 2 — $meta in find() With Sort

The same pattern works in a standard find() query:

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

How It Works

The second argument to find() is the projection. Include { score: { $meta: "textScore" } } to add the relevance field, then chain .sort() with the same meta reference.

Example 3 — $meta in $addFields

Add a relevance field without removing other fields:

mongosh
db.articles.aggregate([
  {
    $match: {
      $text: { $search: "tutorial" }
    }
  },
  {
    $addFields: {
      relevance: { $meta: "textScore" }
    }
  },
  {
    $sort: { relevance: -1 }
  }
])

How It Works

$addFields keeps all existing fields and adds relevance. After projecting with $meta, you can sort by the field name directly (relevance: -1) in later stages.

Example 4 — Filter by Minimum Relevance Score

Keep only results above a score threshold using $match after projecting:

mongosh
db.articles.aggregate([
  {
    $match: {
      $text: { $search: "mongodb" }
    }
  },
  {
    $addFields: {
      score: { $meta: "textScore" }
    }
  },
  {
    $match: {
      score: { $gte: 1.0 }
    }
  },
  {
    $sort: { score: -1 }
  }
])

How It Works

Project textScore first, then filter on the numeric score field. This helps remove weak matches from search results.

Bonus — Label Results by Score Tier

Project the score first, then categorize match quality in a second stage:

mongosh
db.articles.aggregate([
  {
    $match: {
      $text: { $search: "mongodb" }
    }
  },
  {
    $addFields: {
      score: { $meta: "textScore" }
    }
  },
  {
    $addFields: {
      matchQuality: {
        $cond: [
          { $gte: [ "$score", 2 ] },
          "strong",
          "weak"
        ]
      }
    }
  }
])

How It Works

Add textScore with $meta first, then use the numeric score field in $cond. Threshold values depend on your data and index — tune them with sample queries.

🚀 Use Cases

  • Search ranking — show the most relevant articles, products, or posts first.
  • Debugging search — expose textScore during development to tune queries and indexes.
  • Quality filtering — drop low-scoring matches before returning results to users.
  • Search analytics — log relevance scores to understand query performance over time.

🧠 How $meta Works

1

Text index + $text query

MongoDB runs a full-text search and computes a relevance score per matching document.

Search
2

$meta requests metadata

In $project or find projection, { $meta: "textScore" } exposes the score as a field.

Project
3

Sort by relevance

Use { $meta: "textScore" } in $sort or sort by the projected field name.

Rank
=

Ranked search results

Users see documents ordered by how well they match the search terms.

Conclusion

The $meta operator connects full-text search to usable relevance ranking. With a text index, a $text query, and { $meta: "textScore" } in your projection, you can surface and sort by match quality.

For beginners, remember the three-part pattern: index, $text match, and $meta project/sort. Without all three, textScore will not work as expected.

💡 Best Practices

✅ Do

  • Create a text index before using $text and $meta
  • Project textScore when users need ranked search results
  • Sort by { $meta: "textScore" } or the projected score field
  • Test search terms and tune index fields (title, body, etc.)
  • Filter weak matches with a minimum score when appropriate

❌ Don’t

  • Use textScore without a $text query in the same operation
  • Expect $meta to work like a general expression operator
  • Forget that only one $text expression is allowed per query
  • Confuse classic $text search with MongoDB Atlas Search (different API)
  • Assume score values are comparable across different search terms

Key Takeaways

Knowledge Unlocked

Five things to remember about $meta

Use these points when building text search in MongoDB.

5
Core concepts
📝 02

textScore

Relevance value.

Syntax
🛠 03

Needs $text

Search required.

Prerequisite
🔄 04

Project + Sort

Expose & rank.

Pattern
📑 05

Text Index

Create first.

Setup

❓ Frequently Asked Questions

$meta returns metadata about a document in a projection or sort. The most common value is "textScore", which gives the relevance score from a $text full-text search query.
In a projection: { score: { $meta: "textScore" } }. In a sort: { score: { $meta: "textScore" } }. It is used alongside a query that includes $text: { $search: "..." }.
You need a text index on the searched fields, a query with $text, and then $meta: "textScore" in $project or sort. Without $text in the query, textScore is not available.
Yes. In find(), pass { field: { $meta: "textScore" } } in the projection document. In aggregation, use the same form inside $project or $addFields, and sort with { $meta: "textScore" }.
Add a sort stage or .sort() with { score: { $meta: "textScore" } } where score is the field name you assigned in the projection. Use -1 for highest relevance first.

Continue the Operator Series

Move on to $millisecond for date part extraction, or review $map for array transforms.

Next: $millisecond →

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