$count(聚合)
定义
兼容性
您可以在以下环境中使用 $count
MongoDB Atlas:云中 MongoDB 部署的全托管服务
MongoDB 企业版:基于订阅的自托管 MongoDB 版本
MongoDB 社区版:源代码可用的 MongoDB 版本,免费使用且可自托管
语法
$count
的语法如下
{ $count: <string> }
<string>
是输出字段的名称,该字段的值为计数。 <string>
必须是非空字符串,不能以$
开头,且不能包含.
字符。
行为
返回类型表示可以存储计数最终值的类型中最小的类型:整数
→ 长整数
→ 双精度浮点数
$count
阶段等价于以下$group
和$project
序列
db.collection.aggregate( [ { $group: { _id: null, myCount: { $sum: 1 } } }, { $project: { _id: 0 } } ] )
myCount
是存储计数的输出字段。您可以为输出字段指定另一个名称。
如果输入数据集为空,$count
不会返回结果。
示例
使用以下文档创建名为 scores
的集合
db.scores.insertMany( [ { "_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 } ] )
以下聚合操作分为两个阶段
$match
阶段排除了具有小于或等于80
分的分数的文档,以将具有大于80
分的分数的文档传递到下一阶段。$count
阶段返回聚合管道中剩余文档的数量,并将该值赋给名为passing_scores
的字段。
db.scores.aggregate( [ { $match: { score: { $gt: 80 } } }, { $count: "passing_scores" } ] )
此操作返回此结果
{ "passing_scores" : 4 }
如果输入数据集为空,$count
不返回结果。以下示例不返回结果,因为没有分数大于 99
的文档
db.scores.aggregate( [ { $match: { score: { $gt: 99 } } }, { $count: "high_scores" } ] )