$comment

On this page本页内容

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将注释附加到查找

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

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日志中。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" } } }
] )
←  Miscellaneous Query Operators$rand →