$count (aggregation)
On this page本页内容
Definition定义
$count
-
Passes a document to the next stage that contains a count of the number of documents input to the stage.将文档传递到下一个阶段,该阶段包含输入到该阶段的文档数的计数。NoteDisambiguation消除歧义This page describes the本页介绍$count
aggregation pipeline stage.$count
聚合管道阶段。For the有关$count
aggregation accumulator, see$count (aggregation accumulator)
.$count
聚合累加器的信息,请参阅$count
(聚合累加器)。$count
has the following prototype form:具有以下原型形式:{ $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 $count
stage is equivalent to the following $group
+ $project
sequence:$count
阶段相当于以下$group
+$project
序列:
db.collection.aggregate( [
{ $group: { _id: null, myCount: { $sum: 1 } } },
{ $project: { _id: 0 } }
] )
where 其中myCount
would be the output field that contains the count. You can specify another name for the output field.myCount
将是包含计数的输出字段。您可以为输出字段指定另一个名称。
See also: 另请参阅:
db.collection.countDocuments()
which wraps the 它用$group
aggregation stage with a $sum
expression.$sum
表达式封装$group
聚合阶段。
Example实例
A collection named 一个名为scores
has the following documents:scores
的集合包含以下文档:
{ "_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:以下聚合操作有两个阶段:
The$match
stage excludes documents that have ascore
value of less than or equal to80
to pass along the documents withscore
greater than80
to the next stage.$match
阶段排除得score
小于或等于80
的文档,以便将score
大于80
的文档传递到下一阶段。The$count
stage returns a count of the remaining documents in the aggregation pipeline and assigns the value to a field calledpassing_scores
.$count
阶段返回聚合管道中剩余文档的计数,并将值分配给名为passing_scores
的字段。
db.scores.aggregate(
[
{
$match: {
score: {
$gt: 80
}
}
},
{
$count: "passing_scores"
}
]
)
The operation returns the following results:该操作返回以下结果:
{ "passing_scores" : 4 }