Definition 定义
将包含输入到该 stage 的文档数量的文档传递到下一个 stage。
NOTE 歧义澄清(Disambiguation) 本页描述了
$countaggregation pipeline stage。关于$countaggregation accumulator(聚合累加器),参阅 $count(aggregation accumulator)。
$count的原型形式如下:
{ $count: <string> }
<string>是输出字段的名称,该字段以计数(输入文档的数量)为其值。<string>必须是一个非空的字符串,不能以$开头,也不能包含.字符。
TIP 参阅:
Behavior 行为
$countstage 相当于下面的 $group + $project 序列(sequence)。
db.collection.aggregate( [{ $group: { _id: null, myCount: { $sum: 1 } } },{ $project: { _id: 0 } }] )
其中myCount是包含计数(输入文档的数量)的输出字段。你可以为输出字段指定另一个名称。
TIP 参阅: db.collection.countDocuments() 它用一个 $sum expression 包装了 $group aggregation stage。
Example 例子
一个名为scores的 collection 有以下文档:
{ "_id" : 1, "subject" : "History", "score" : 88 }{ "_id" : 2, "subject" : "History", "score" : 92 }{ "_id" : 3, "subject" : "History", "score" : 97 }{ "_id" : 4, "subject" : "History", "score" : 71 }{ "_id" : 5, "subject" : "History", "score" : 79 }{ "_id" : 6, "subject" : "History", "score" : 83 }
下面的 aggregation operation 有两个 stage:
- $match stage 排除
score值小于或等于80的文档,将score大于80的文档传递到下一个 stage。 $countstage 返回 aggregation pipeline 中剩余文档的数量,并将该值分配给一个叫做passing_scores的字段。
该 operation 返回以下结果:db.scores.aggregate( [{$match: {score: {$gt: 80}}},{$count: "passing_scores"}] )
{ "passing_scores": 4 }
参考
https://docs.mongodb.com/manual/reference/operator/aggregation/count
