0
0
MongoDBquery~10 mins

$count accumulator in MongoDB - Step-by-Step Execution

Choose your learning style9 modes available
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.
Execution Sample
MongoDB
db.collection.aggregate([
  { $group: { _id: null, total: { $sum: 1 } } }
])
Counts all documents in the collection and outputs the total count as 'total'.
Execution Table
StepDocument Processed$count ValueActionOutput
1{_id: 1, name: 'Alice'}1Increment count by 1No output yet
2{_id: 2, name: 'Bob'}2Increment count by 1No output yet
3{_id: 3, name: 'Charlie'}3Increment count by 1No output yet
4No more documents3Output total count{_id: null, total: 3}
💡 All documents processed, $count outputs the total count 3.
Variable Tracker
VariableStartAfter 1After 2After 3Final
$count01233
Key Moments - 2 Insights
Why does $count output only once at the end instead of after each document?
$count accumulates the count internally as documents pass through. It outputs only once after processing all documents, as shown in execution_table row 4.
Can $count be used without $group stage?
$count is an accumulator and must be used inside a $group stage, as in the example code. It cannot be used alone.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the $count value after processing the second document?
A1
B3
C2
D0
💡 Hint
Check the $count Value column at Step 2 in the execution_table.
At which step does the $count accumulator output the total count?
AStep 4
BStep 1
CStep 3
DStep 2
💡 Hint
Look for the step where 'Output total count' action happens in the execution_table.
If the collection had 5 documents instead of 3, what would be the final $count value?
A4
B5
C3
D6
💡 Hint
Refer to variable_tracker showing $count increments per document.
Concept Snapshot
$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.
Full Transcript
The $count accumulator in MongoDB aggregation counts how many documents pass through the pipeline. It is used inside a $group stage to accumulate a total count. As each document is processed, $count increments by one. It does not output intermediate counts but only outputs the final total count after all documents are processed. For example, if there are three documents, $count increments from 0 to 3, then outputs {total: 3}. This accumulator is useful to find the number of documents matching certain criteria in aggregation pipelines.