For AI agents: a documentation index is available at https://www.mongodb.com/ja-jp/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Docs Menu

$count (aggregation stage)

$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 $count aggregation pipeline stage. You can also use $count in these other contexts:

You can use $count for deployments hosted in the following environments:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

$count has the following syntax:

{ $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.

The return type is represented by the smallest type that can store the final value of count: integer → long → double

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

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

myCount is the output field that stores the count. You can specify another name for the output field.

If the input dataset is empty, $count doesn't return a result.

Tip

db.collection.countDocuments() wraps the $group aggregation stage with a $sum expression.

The examples on this page use data from the sample_mflix dataset. For details on how to load this dataset into your self-managed MongoDB deployment, see Load the Sample Dataset. If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.

The following aggregation operation has two stages:

  1. The $match stage filters for documents where metacritic equals 100 to pass along only those documents to the next stage.

  2. The $count stage returns a count of the remaining documents in the aggregation pipeline and assigns the value to a field called perfect_score_count.

db.movies.aggregate( [
{ $match: { metacritic: { $eq: 100 } } },
{ $count: "perfect_score_count" }
] )
[ { perfect_score_count: 8 } ]