$count

The `$count` operator is used to count the number of documents that match a specified query filter. The count operator is useful for summarizing data or generating counts for specific groupings.

Syntax

{
  $count: "<fieldName>"
}

Parameters

fieldNamestringrequired

The name of the field in the output document where the count will be stored.

Examples

Sample Data

{
  "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
  "name": "First Up Consultants | Beverage Shop",
  "sales": {
    "salesByCategory": [
      { "categoryName": "Wine Accessories" }
    ]
  },
  "promotionEvents": [
    { "eventName": "Unbeatable Bargain Bash" }
  ]
}

Retrieve the count of all documents

Count all documents in the collection without any filters.

This query uses $count to return the total number of documents.

Query:

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

Output:

[
  { "totalDocuments": 41501 }
]

Count documents grouped by a specific field

Count documents within each sales category by grouping and counting.

This query unwinds categories, groups by category name, and counts documents per category.

Query:

db.stores.aggregate([
  { $unwind: "$sales.salesByCategory" },
  {
    $group: {
      _id: "$sales.salesByCategory.categoryName",
      totalCount: { $count: {} }
    }
  }
])

Output:

[
  { "_id": "Christmas Trees", "totalCount": 93 },
  { "_id": "Nuts", "totalCount": 83 },
  { "_id": "Camping Tables", "totalCount": 130 }
]

Count the number of promotion events

Count all promotion events across stores by unwinding and counting.

This query unwinds the promotionEvents array and counts total events.

Query:

db.stores.aggregate([
  { $unwind: "$promotionEvents" },
  { $count: "totalPromotionEvents" }
])

Output:

[
  { "totalPromotionEvents": 145673 }
]

Related