0
0
MongodbHow-ToBeginner · 3 min read

How to Use $count in Aggregation in MongoDB

In MongoDB aggregation, use the $count stage to count the number of documents passing through the pipeline and return the count as a field. It outputs a single document with the count value under the specified field name.
📐

Syntax

The $count stage in an aggregation pipeline counts the number of documents and outputs a document with a single field containing that count.

Syntax:

{ $count: "fieldName" }

Here, fieldName is the name of the field in the output document that will hold the count number.

json
{ $count: "total" }
💻

Example

This example counts how many documents are in the orders collection using an aggregation pipeline with $count.

mongodb
db.orders.aggregate([
  { $count: "orderCount" }
])
Output
[ { "orderCount" : 5 } ]
⚠️

Common Pitfalls

Common mistakes when using $count include:

  • Using $count without specifying a field name, which causes an error.
  • Placing $count before filtering stages, which counts all documents instead of filtered ones.
  • Expecting $count to return multiple documents; it always returns a single document with the count.
mongodb
/* Wrong: missing field name */
db.orders.aggregate([
  { $count: "" }
])

/* Correct: specify field name */
db.orders.aggregate([
  { $count: "totalOrders" }
])
📊

Quick Reference

StageDescriptionExample
$countCounts documents and outputs a single document with the count{ $count: "countField" }
UsagePlace after filtering stages to count filtered documentsdb.collection.aggregate([ { $match: {...} }, { $count: "count" } ])
OutputSingle document with count field{ "countField": 10 }

Key Takeaways

Use $count with a field name to get the number of documents in aggregation.
$count outputs a single document with the count under the specified field.
Place $count after filtering stages to count only matching documents.
Always specify a field name inside $count to avoid errors.
$count does not return multiple documents, only one with the total count.