MongoDB Atlas 6.0.8中聚合管道使用$comment报错求助
MongoDB聚合管道添加注释的正确写法
你之前的两种写法都不符合MongoDB 6.0的语法要求,错误原因和修正方案如下:
错误原因分析
- 写法1:聚合管道的每个阶段对象只能包含一个顶级字段,你把
$match和$comment放在同一个对象里,违反了这个规则,所以报错"A pipeline stage specification object must contain exactly one field." - 写法2:
$comment不是独立的聚合管道阶段运算符,不能单独作为一个阶段存在,因此报错"$comment is not allowed or the syntax is incorrect..."
正确写法
方法1:作为聚合方法的选项参数传递
将注释作为aggregate()方法的第二个参数(选项对象)传入,这是最通用的方式:
db.aCollection.aggregate( [{"$match": {"a": true}}], {"comment": "some comment"} )
方法2:在支持的聚合阶段内部嵌入$comment
部分聚合阶段(如$match、$group等)支持在阶段内部使用$comment字段,写法如下:
db.aCollection.aggregate([ {"$match": {"a": true, "$comment": "some comment"}} ])
内容的提问来源于stack exchange,提问作者Màrius Rak
相关产品推荐
相关产品推荐

