Database Manual / Reference / Query Language / Aggregation Stages

$count (aggregation stage)(聚合阶段)

Definition定义

$count

Passes a document to the next stage that contains a count of the number of documents input to the stage.将文档传递到下一阶段,该阶段包含输入到该阶段的文档数量的计数。

Note

Disambiguation消歧

This page describes the $count aggregation pipeline stage. For the $count aggregation accumulator, see $count (aggregation accumulator).此页面描述了$count聚合管道阶段。关于$count聚合累加器,请参阅$count(聚合累加器)

Compatibility兼容性

You can use $count for deployments hosted in the following environments:您可以将$count用于在以下环境中托管的部署:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Syntax语法

$count has the following syntax:具有以下语法:

{ $count: <string> }

<string> is the name of the output field which has the count as its value. 是以计数为值的输出字段的名称。<string> must be a non-empty string, must not start with $ and must not contain the . character.必须是非空字符串,不得以$开头,且不得包含.字符。

Behavior行为

The return type is represented by the smallest type that can store the final value of count: 返回类型由可以存储count最终值的最小类型表示:integerlongdouble

The $count stage is equivalent to the following $group and $project sequence:$count阶段相当于以下$group$project序列:

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

myCount is the output field that stores the count. You can specify another name for the output field.myCount是存储计数的输出字段。您可以为输出字段指定另一个名称。

If the input dataset is empty, $count doesn't return a result.如果输入数据集为空,$count不会返回结果。

Tip

db.collection.countDocuments() wraps the $group aggregation stage with a $sum expression.$sum表达式包装$group聚合阶段。

Examples示例

MongoDB Shell

Create a collection named scores with these documents:使用以下文档创建一个名为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 }
] )

The following aggregation operation has two stages:以下聚合操作分为两个阶段:

  1. The $match stage excludes documents that have a score value of less than or equal to 80 to pass along the documents with score greater than 80 to the next stage.$match阶段不包括得80小于或等于80的文档,将80大于80的文档传递到下一阶段。
  2. The $count stage returns a count of the remaining documents in the aggregation pipeline and assigns the value to a field called passing_scores.$count阶段返回聚合管道中剩余文档的计数,并将该值分配给名为passing_scores的字段。
db.scores.aggregate( [
{ $match: { score: { $gt: 80 } } },
{ $count: "passing_scores" }
] )

The operation returns this result:该操作返回以下结果:

{ "passing_scores" : 4 }

If the input dataset is empty, $count doesn't return a result. The following example doesn't return a result because there are no documents with scores greater than 99:如果输入数据集为空,$count不会返回结果。以下示例不返回结果,因为没有得分大于99的文档:

db.scores.aggregate( [
   { $match: { score: { $gt: 99 } } },
{ $count: "high_scores" }
] )
C#

The C# examples on this page use the sample_mflix database from the Atlas sample datasets. 本页上的C#示例使用Atlas示例数据集中的sample_mflix数据库。To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see Get Started in the MongoDB .NET/C# Driver documentation.要了解如何创建免费的MongoDB Atlas集群并加载示例数据集,请参阅MongoDB .NET/C#驱动程序文档中的入门

The following Movie class models the documents in the sample_mflix.movies collection:以下Movie类对sample_mflix.movies集合中的文档进行建模:

public class Movie
{
public ObjectId Id { get; set; }

public int Runtime { get; set; }

public string Title { get; set; }

public string Rated { get; set; }

public List<string> Genres { get; set; }

public string Plot { get; set; }

public ImdbData Imdb { get; set; }

public int Year { get; set; }

public int Index { get; set; }

public string[] Comments { get; set; }

[BsonElement("lastupdated")]
public DateTime LastUpdated { get; set; }
}

Note

ConventionPack for Pascal CasePascal案例的约定包

The C# classes on this page use Pascal case for their property names, but the field names in the MongoDB collection use camel case. To account for this difference, you can use the following code to register a ConventionPack when your application starts:此页面上的C#类使用Pascal大小写作为其属性名,但MongoDB集合中的字段名使用驼峰大小写。为了解释这种差异,您可以在应用程序启动时使用以下代码注册ConventionPack

var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);

To use the MongoDB .NET/C# driver to add a $count stage to an aggregation pipeline, call the Count() method on a PipelineDefinition object.要使用MongoDB .NET/C#驱动程序向聚合管道添加$count阶段,请在PipelineDefinition对象上调用Count()方法。

The following example creates a pipeline stage that counts the number of input documents and returns a document with the count as its value:以下示例创建了一个管道阶段,该阶段对输入文档的数量进行计数,并返回一个以计数为值的文档:

var pipeline = new EmptyPipelineDefinition<Movie>()
.Count();
Node.js

The Node.js examples on this page use the sample_mflix database from the Atlas sample datasets. 本页上的Node.js示例使用Atlas示例数据集中的sample_mflix数据库。To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see Get Started in the MongoDB Node.js driver documentation.要了解如何创建免费的MongoDB Atlas集群并加载示例数据集,请参阅MongoDB Node.js驱动程序文档中的入门

To use the MongoDB Node.js driver to add a $count stage to an aggregation pipeline, use the $count operator in a pipeline object.要使用MongoDB Node.js驱动程序向聚合管道添加$count阶段,请在管道对象中使用$count运算符。

The following example creates a pipeline stage that counts the number of input documents from the sample_mflix.movies collection and returns a document containing the count. 以下示例创建了一个管道阶段,该阶段对sample_mflix.movies集合中的输入文档数量进行计数,并返回一个包含该计数的文档。The example then runs the aggregation pipeline:然后,该示例运行聚合管道:

const pipeline = [{ $count: "movies" }];

const cursor = collection.aggregate(pipeline);
return cursor;

Learn More了解更多