🍃 MongoDB Tutorial

MongoDB $comment Operator: Tagging Queries for Debugging

Learn how MongoDB's $comment operator lets you attach a note to a query so it's easy to identify later in logs and the profiler.

The $comment Operator

The $comment operator attaches a human-readable note to a query. It doesn't affect the results at all — its only job is to make the query easier to recognize later in MongoDB's logs or the database profiler, which is genuinely useful once an app has dozens of similar-looking queries running in production.

Syntax

db.collection.find({ <query>, $comment: <comment> })

Example

db.employees.find({ "city": { $eq: "Palghar" } })

// same query, but tagged for easy tracing in the logs
db.employees.find({
  "city": { $eq: "Palghar" },
  $comment: "Find City Palghar"
})

There's also a chained .comment() method that does the same thing:

db.employees.find().comment("Find query for employees")

db.employees.find({ city: "Pune" })
  .comment("Find query for employees collection to find whose city is pune")

Common Errors & Troubleshooting

  • Expecting $comment to change query results — it never filters or affects matching in any way; if your query returns unexpected results, the problem is elsewhere in the query, not the comment.
  • Forgetting $comment needs to be inside the same query object — it must sit alongside your other conditions in the query document passed to find(), not as a separate argument.

Key Takeaways

  • $comment is purely for observability — it never changes which documents are returned.
  • Use it on queries you'll want to identify quickly in mongod logs or db.currentOp().