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
$countwithout specifying a field name, which causes an error. - Placing
$countbefore filtering stages, which counts all documents instead of filtered ones. - Expecting
$countto 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
| Stage | Description | Example |
|---|---|---|
| $count | Counts documents and outputs a single document with the count | { $count: "countField" } |
| Usage | Place after filtering stages to count filtered documents | db.collection.aggregate([ { $match: {...} }, { $count: "count" } ]) |
| Output | Single 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.