Docs 菜单

Docs 主页开发应用程序MongoDB Manual

$comment

在此页面上

  • 定义
  • 行为
  • 举例
$comment

$comment查询运算符将注释与采用查询谓词的任何表达式相关联。

由于注释会传输到 profile 日志,因此添加注释可使配置文件数据更易于解释和跟踪。

$comment操作符的形式为:

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

您可以将$comment 与任何采用查询谓词的表达式一起使用,例如db.collection.updateOne() 中或$match 聚合管道 的 阶段中的查询谓词。有关示例,请参阅 将注释附加到聚合表达式。

以下示例将$comment添加到find()操作:

db.records.find(
{
x: { $mod: [ 2, 0 ] },
$comment: "Find even values."
}
)

如果启用了数据库分析器,则以下输出显示 system.profile 集合中的注释:

{
"op" : "query",
"ns" : "test.records",
"command" : {
"find" : "records",
"filter" : {
"x" : {
"$mod" : [
2,
0
]
},
"$comment" : "Find even values."
},
"comment" : "Find even values.",
...

如果数据库分析器级别设置为 2 并且 slowms 设置为 0 ms,则注释还会显示在 MongoDB 日志中。此 db.setProfilingLevel() 命令设置这两个参数:

db.setProfilingLevel(2, 0)

MongoDB 日志中,上一个 db.records.find() 示例的注释如下所示:

{"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."
...

您可以将$comment与任何采用查询谓词的表达式一起使用。

以下示例在 阶段使用$comment $match操作符来阐明操作:

db.records.aggregate( [
{ $match: { x: { $gt: 0 }, $comment: "Don't allow negative inputs." } },
{ $group : { _id: { $mod: [ "$x", 2 ] }, total: { $sum: "$x" } } }
] )
← 其他查询操作符
$rand →

在此页面上