$count (aggregation)

Definition

  • $count

New in version 3.4.

Passes a document to the next stage that contains a count of thenumber of documents input to the stage.

$count has the following prototype form:

  1. { $count: <string> }

<string> is the name of the output field which has the countas its value. <string> must be a non-empty string, must notstart with $ and must not contain the . character.

See also

Behavior

The $count stage is equivalent to the following$group + $project sequence:

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

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:

  1. { "_id" : 1, "subject" : "History", "score" : 88 }
  2. { "_id" : 2, "subject" : "History", "score" : 92 }
  3. { "_id" : 3, "subject" : "History", "score" : 97 }
  4. { "_id" : 4, "subject" : "History", "score" : 71 }
  5. { "_id" : 5, "subject" : "History", "score" : 79 }
  6. { "_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 to 80 to pass along thedocuments with score greater than 80 to the nextstage.
  • The $count stage returns a count of the remaining documentsin the aggregation pipeline and assigns the value to a field calledpassing_scores.
  1. db.scores.aggregate(
  2. [
  3. {
  4. $match: {
  5. score: {
  6. $gt: 80
  7. }
  8. }
  9. },
  10. {
  11. $count: "passing_scores"
  12. }
  13. ]
  14. )

The operation returns the following results:

  1. { "passing_scores" : 4 }