文档菜单
文档首页
/
MongoDB 手册
/ / /

$count(聚合)

本页

  • 定义
  • 兼容性
  • 语法
  • 行为
  • 示例
  • 了解更多
$count

将包含输入到该阶段文档数量的计数传递到下一阶段。

注意

消除歧义

本页描述了 $count 聚合管道阶段。有关 $count 聚合累加器,请参阅$count(聚合累加器).

您可以在以下环境中使用 $count

  • MongoDB Atlas:云中 MongoDB 部署的全托管服务

$count的语法如下

{ $count: <string> }

<string>是输出字段的名称,该字段的值为计数。 <string>必须是非空字符串,不能以$开头,且不能包含.字符。

返回类型表示可以存储计数最终值的类型中最小的类型:整数长整数双精度浮点数

$count阶段等价于以下$group$project序列

db.collection.aggregate( [
{ $group: { _id: null, myCount: { $sum: 1 } } },
{ $project: { _id: 0 } }
] )

myCount是存储计数的输出字段。您可以为输出字段指定另一个名称。

如果输入数据集为空,$count不会返回结果。

提示

另请参阅

db.collection.countDocuments(),该函数用$group聚合阶段和$sum表达式包装。

使用以下文档创建名为 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 }
] )

以下聚合操作分为两个阶段

  1. $match 阶段排除了具有小于或等于 80 分的分数的文档,以将具有大于 80 分的分数的文档传递到下一阶段。

  2. $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" }
] )

返回

$collStats