- Reference >
- Operators >
- Aggregation Pipeline Stages >
- $count (aggregation)
$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.
Note
Disambiguation
This page describes the
$countaggregation pipeline stage. For the$countaggregation accumulator, see$count (aggregation accumulator).$counthas the following prototype form:<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:
where myCount would be the output field that contains the count.
You can specify another name for the output field.
See also
db.collection.countDocuments() which wraps the
$group aggregation stage with a $sum expression.
Example¶
A collection named scores has the following documents:
The following aggregation operation has two stages:
- The
$matchstage excludes documents that have ascorevalue of less than or equal to80to pass along the documents withscoregreater than80to the next stage. - The
$countstage returns a count of the remaining documents in the aggregation pipeline and assigns the value to a field calledpassing_scores.
The operation returns the following results: