Concept Flow - $count accumulator
Start Aggregation Pipeline
Process Each Document
$count Accumulator Increments
Output Total Count
End
The $count accumulator counts each document passing through the pipeline and outputs the total count at the end.
db.collection.aggregate([
{ $group: { _id: null, total: { $sum: 1 } } }
])| Step | Document Processed | $count Value | Action | Output |
|---|---|---|---|---|
| 1 | {_id: 1, name: 'Alice'} | 1 | Increment count by 1 | No output yet |
| 2 | {_id: 2, name: 'Bob'} | 2 | Increment count by 1 | No output yet |
| 3 | {_id: 3, name: 'Charlie'} | 3 | Increment count by 1 | No output yet |
| 4 | No more documents | 3 | Output total count | {_id: null, total: 3} |
| Variable | Start | After 1 | After 2 | After 3 | Final |
|---|---|---|---|---|---|
| $count | 0 | 1 | 2 | 3 | 3 |
$count accumulator counts documents in a $group stage.
Syntax: { $group: { _id: null, total: { $sum: 1 } } }
Counts each document passing through.
Outputs total count once after all documents.
Must be used inside $group stage.$count accumulator do in a MongoDB aggregation pipeline?$count$count accumulator is used inside the $group stage to count how many documents belong to each group.$sum, $max, or $avg, $count does not operate on field values but counts documents.$count = document count [OK]$count in a $group stage?$count syntax$count accumulator does not take any arguments inside its braces; it should be empty: { $count: {} }.$count, which is invalid syntax.{ "category": "A" }, { "category": "B" }, { "category": "A" }[ { $group: { _id: "$category", count: { $count: {} } } } ]$count accumulator is not valid inside a $group stage. It is a separate pipeline stage used to count total documents, not per group.$sum: 1 inside $group, not $count.$count inside $group$count inside $group causes a syntax error.$count is a pipeline stage, not an accumulator [OK][ { $group: { _id: "$type", total: { $count: "$amount" } } } ]$count accumulator does not accept any arguments; passing "$amount" is invalid syntax.$count to achieve this?$count is not valid inside $group, use $sum: 1 to count documents per group.$match after grouping to filter customers with orderCount greater than 2.Pass the test and this pattern moves unknown