Docs HomeMongoDB Manual

$comment

Definition定义

$comment

The $comment query operator associates a comment to any expression taking a query predicate.$comment查询运算符将注释与采用查询谓词的任何表达式相关联。

Because comments propagate to the profile log, adding a comment can make your profile data easier to interpret and trace.由于注释会传播到profile文件日志,因此添加注释可以使配置文件数据更易于解释和跟踪。

The $comment operator has the form:$comment运算符的形式如下:

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. 您可以将$comment与任何接受查询谓词的表达式一起使用,例如db.collection.updateOne()或聚合管道的$match阶段中的查询谓词。For an example, see Attach a Comment to an Aggregation Expression.有关示例,请参阅将注释附加到聚合表达式

Examples实例

Attach a Comment to find附加要find的注释

The following example adds a $comment to a find() operation:以下示例向find()操作添加$comment

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:如果启用了数据库档案器,则以下输出将显示system.profile集合中的注释:

{
"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. 如果数据库探查器级别设置为2,slowms设置为0ms,则注释也会出现在MongoDB log中。This db.setProfilingLevel() command sets these two parameters:这个db.setProfilingLevel()命令设置以下两个参数:

db.setProfilingLevel(2, 0)

The comment for the previous db.records.find() example then appears as follows in the MongoDB log:上一个db.records.find()示例的注释随后显示在MongoDB日志中,如下所示:

{"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.您可以将$comment与采用查询谓词的任何表达式一起使用。

The following example uses the $comment operator in the $match stage to clarify the operation:以下示例在$match阶段使用$comment运算符来澄清操作:

db.records.aggregate( [
{ $match: { x: { $gt: 0 }, $comment: "Don't allow negative inputs." } },
{ $group : { _id: { $mod: [ "$x", 2 ] }, total: { $sum: "$x" } } }
] )