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.