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")
Advertisement728 x 90
Common Errors & Troubleshooting
- Expecting
$commentto 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
$commentneeds to be inside the same query object — it must sit alongside your other conditions in the query document passed tofind(), not as a separate argument.
Key Takeaways
$commentis purely for observability — it never changes which documents are returned.- Use it on queries you'll want to identify quickly in
mongodlogs ordb.currentOp().
Advertisement320 x 100