$count (aggregation)

在本页面

Definition

$count具有以下原型形式:

{ $count: <string> }

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

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 }

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

db.scores.aggregate(
  [
    {
      $match: {
        score: {
          $gt: 80
        }
      }
    },
    {
      $count: "passing_scores"
    }
  ]
)

该操作返回以下结果:

{ "passing_scores" : 4 }
首页