MongoDB $comment Operator

Beginner
⏱️ 7 min read
📚 Updated: Jul 2026
🎯 4 Examples
Debugging

What You’ll Learn

The $comment operator attaches a descriptive label to a MongoDB query. It does not change your data — it helps you find and debug operations in the profiler, logs, and currentOp output.

01

Query Labels

Annotate operations.

02

No Data Change

Observability only.

03

In $match

Inside query predicates.

04

Aggregate Option

Label whole pipeline.

05

Profiler

Trace slow queries.

06

Not JS Comments

Runs on the server.

Definition and Usage

The $comment operator associates a human-readable string with a query predicate. When you enable profiling or inspect server logs, the comment appears next to the operation so you can tell which part of your app issued the query — without guessing from raw BSON.

💡
Beginner Tip

$comment is different from operators like $abs or $cmp. It does not compute a value or transform documents. Think of it as a sticky note on your query for debugging and monitoring.

📝 Syntax

There are two common ways to add comments in aggregation workflows:

1. Inside a query predicate (e.g. $match)

mongosh
{ $match: { <field>: <value>, $comment: "Your comment here" } }

2. As an option on aggregate()

mongosh
db.collection.aggregate(
  [ /* pipeline stages */ ],
  { comment: "Your comment here" }
)

Syntax Rules

  • $comment — a string (or any valid BSON type) describing the operation.
  • Use inside expressions that accept query predicates: $match, find, updateOne, etc.
  • The comment option on aggregate() labels the entire command.
  • Comments appear in profiler output, logs, and db.currentOp().
  • Comments do not filter documents or affect query results.

💡 $comment Does Not Transform Data

Unlike math or string operators, $comment is purely for observability:

With $comment — same documents returned
Without $comment — same documents returned
Difference — only visible in profiler, logs, and currentOp

⚡ Quick Reference

QuestionAnswer
Operator typeQuery modifier (observability)
In $match{ $match: { ..., $comment: "text" } }
On aggregate(){ comment: "text" } as second argument
Affects results?No
Visible inProfiler, logs, currentOp
$match
$comment: "dashboard"

Label a filter stage

aggregate()
{
  comment: "..."
}

Label whole pipeline

find()
.comment("...")

mongosh helper

Profiler
command.comment

Search by comment

Examples Gallery

Annotate aggregation pipelines, find queries, and profiler lookups with meaningful comments.

📚 Annotate Queries

Add $comment inside a $match stage to label a specific filter in your pipeline.

Example 1 — $comment Inside $match

Attach a comment to explain why a filter exists:

mongosh
db.orders.aggregate([
  {
    $match: {
      status: "open",
      $comment: "Dashboard: fetch open orders for summary widget"
    }
  },
  {
    $group: {
      _id: "$region",
      total: { $sum: "$amount" }
    }
  }
])

How It Works

The $comment field sits alongside your filter conditions. MongoDB ignores it for matching but records it in profiler and log output when the query runs.

📈 Practical Patterns

Label entire pipelines, use mongosh helpers, and search the profiler by comment text.

Example 2 — Comment Option on aggregate()

Label the entire aggregation command (recommended for pipeline-wide tracking):

mongosh
db.movies.aggregate(
  [
    { $match: { year: 1995 } },
    { $limit: 10 },
    { $project: { title: 1, year: 1 } }
  ],
  { comment: "Admin report: top 10 movies from 1995" }
)

How It Works

The second argument to aggregate() is an options document. The comment field labels the whole operation and is inherited by subsequent getMore cursor commands.

Example 3 — find().comment() in mongosh

For simple find queries, mongosh provides a chainable .comment() method:

mongosh
db.users
  .find({ active: true })
  .comment("Nightly job: sync active users")
  .limit(1000)

// Equivalent using $comment in the query document:
db.users.find({
  active: true,
  $comment: "Nightly job: sync active users"
}).limit(1000)

How It Works

Both forms attach the same comment metadata. Use whichever style fits your codebase — the profiler sees the comment either way.

Example 4 — Find Queries in the Profiler by Comment

After enabling profiling, search for operations by their comment string:

mongosh
// Enable profiling (level 1 = slow ops, level 2 = all ops)
db.setProfilingLevel(1, { slowms: 100 })

// Run your annotated query...
db.orders.aggregate(
  [ { $match: { status: "open" } } ],
  { comment: "Dashboard: open orders summary" }
)

// Find it in the profiler
db.system.profile.find({
  "command.comment": "Dashboard: open orders summary"
}).sort({ ts: -1 }).limit(5)

How It Works

Descriptive comments make profiler results self-documenting. Instead of hunting through anonymous pipelines, you filter by command.comment to find exactly the query you need to optimize.

🚀 Use Cases

  • Debugging slow queries — identify which app feature issued an expensive operation.
  • Profiler analysis — filter system.profile by comment to isolate recurring patterns.
  • Production monitoring — correlate currentOp entries with application code paths.
  • Team collaboration — document intent directly in queries shared across developers.

🧠 How $comment Works

1

Your app sends a query with a comment

Via $comment in a predicate or the comment option on aggregate().

Input
2

MongoDB runs the query normally

The comment is metadata only — filtering and pipeline stages execute exactly as before.

Execute
3

The comment is recorded server-side

Profiler entries, log messages, and currentOp include the comment string.

Record
=

Traceable operations

Find, debug, and optimize queries by their descriptive labels.

Conclusion

The $comment operator is a small but valuable tool for query observability in MongoDB. It does not change your results, but it makes debugging, profiling, and production monitoring much easier when you use descriptive labels consistently.

For beginners, remember: use $comment in $match for stage-level notes, use the comment option on aggregate() for pipeline-wide labels, and never put passwords or secrets in comment strings.

💡 Best Practices

✅ Do

  • Use descriptive comments: feature name, report, or job ID
  • Label slow or complex aggregation pipelines
  • Search profiler output by command.comment
  • Use the comment option for whole-pipeline labels
  • Standardize comment format across your team

❌ Don’t

  • Expect $comment to filter or transform data
  • Put passwords, tokens, or PII in comment strings
  • Confuse $comment with JavaScript // comments
  • Use vague labels like "query1" or "test"
  • Forget that comments appear in logs and profiler data

Key Takeaways

Knowledge Unlocked

Five things to remember about $comment

Use these points when annotating MongoDB queries.

5
Core concepts
📝 02

Two Forms

$match or aggregate option.

Syntax
📏 03

No Side Effects

Results unchanged.

Behavior
🛠 04

Profiler

Visible in logs.

Debug
05

Not Transform

Unlike $abs, $cmp.

Important

❓ Frequently Asked Questions

$comment attaches a descriptive string to a query. It does not filter or transform data — it helps you identify operations in the profiler, logs, and currentOp output.
No. $comment is for observability only. Documents returned or modified by the query are exactly the same with or without a comment.
Inside query predicates such as $match in aggregation pipelines, in find/update/delete queries, and as a comment option on db.collection.aggregate().
Comments show up in mongod logs, the database profiler (system.profile), and db.currentOp output — making slow or recurring queries easier to trace.
$comment inside $match annotates that specific filter predicate. The comment option on aggregate() labels the entire aggregation command. Both appear in profiler output.

Continue the Operator Series

Move on to $concat for string concatenation, or review $cmp for value comparison.

Next: $concat →

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