$count

The `$count` stage returns a count of the number of documents at this stage of the aggregation pipeline. It outputs a document with a single field containing the count.

Syntax

{
  $count: <string>
}

Parameters

fieldstringrequired

The name of the output field which contains the count. Must be a non-empty string.

Examples

Sample Data

{
  "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
  "name": "First Up Consultants | Beverage Shop",
  "sales": { "totalSales": 75670 }
}

Count all documents

Count the total number of documents in the collection.

This query returns the total document count.

Query:

db.stores.aggregate([
  { $count: "totalStores" }
])

Output:

[
  { "totalStores": 45505 }
]

Count documents after filtering

Count documents matching specific criteria.

This query counts stores with sales above a threshold.

Query:

db.stores.aggregate([
  { $match: { "sales.totalSales": { $gt: 50000 } } },
  { $count: "highSalesStores" }
])

Output:

[
  { "highSalesStores": 12350 }
]

Related