$comment
On this page
Definition
$comment-
The
$commentquery operator associates a comment to any expression taking a query predicate.Because comments propagate to the
profilelog, adding a comment can make your profile data easier to interpret and trace.The
$commentoperator has the form:db.collection.find( { <query>, $comment: <comment> } )
Behavior
You can use the $comment with any expression taking a query predicate, such as the query predicate in db.collection.updateOne() or in the $match stage of the aggregation pipeline. For an example, see Attach a Comment to an Aggregation Expression.
Examples
Attach a Comment to find
The following example adds a $comment to a find() operation:
db.records.find( { x: { $mod: [ 2, 0 ] }, $comment: "Find even values." } )
If the Database Profiler is enabled, the following output shows the comment in the system.profile collection:
{
"op" : "query",
"ns" : "test.records",
"command" : {
"find" : "records",
"filter" : {
"x" : {
"$mod" : [
2,
0
]
},
"$comment" : "Find even values."
},
"comment" : "Find even values.",
...
Comments also appear in the MongoDB log if the database profiler level is set to 2 and slowms is set to 0ms. This db.setProfilingLevel() command sets these two parameters:
db.setProfilingLevel(2, 0)
The comment for the previous db.records.find() example then appears as follows in the MongoDB log:
{"t":{"$date":"2020-09-17T11:32:20.415-07:00"},"s":"I",
"c":"COMMAND", "id":51803, "ctx":"conn7","msg":"Slow query",
"attr":{"type":"command","ns":"test.records","appName":"MongoDB
Shell","command":{"find":"records","filter":{"x":{"$mod":[2.0,0.0]},
"$comment":"Find even values."},"comment":"Find even values."
...Attach a Comment to an Aggregation Expression
You can use the $comment with any expression taking a query predicate.
The following example uses the $comment operator in the $match stage to clarify the operation:
db.records.aggregate( [ { $match: { x: { $gt: 0 }, $comment: "Don't allow negative inputs." } }, { $group : { _id: { $mod: [ "$x", 2 ] }, total: { $sum: "$x" } } } ] )