On this page
$count (aggregation)
在本页面
Definition
$count
- 返回一个文档,其中包含 Importing 到阶段的文档数量的计数。
$count具有以下原型形式:
{ $count: <string> }
<string>
是具有计数作为其值的输出字段的名称。 <string>
必须是非空字符串,不能以$
开头,并且不能包含.
字符。
See also
Behavior
$count阶段等效于以下$group $project序列:
db.collection.aggregate( [
{ $group: { _id: null, myCount: { $sum: 1 } } },
{ $project: { _id: 0 } }
] )
其中myCount
是包含计数的输出字段。您可以为输出字段指定另一个名称。
Example
名为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 }
以下聚合操作分为两个阶段:
$match
阶段排除score
值小于或等于80
的文档,以将score
大于80
的文档传递到下一个阶段。$count
阶段返回聚合管道中剩余文档的计数,并将该值分配给名为passing_scores
的字段。
db.scores.aggregate(
[
{
$match: {
score: {
$gt: 80
}
}
},
{
$count: "passing_scores"
}
]
)
该操作返回以下结果:
{ "passing_scores" : 4 }