Challenge - 5 Problems
MongoDB $count Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Counting documents with $count accumulator
Given a MongoDB collection orders with documents representing customer orders, what will be the output of this aggregation pipeline?
[{ $match: { status: "completed" } }, { $count: "totalCompleted" }]MongoDB
[{ $match: { status: "completed" } }, { $count: "totalCompleted" }]Attempts:
2 left
💡 Hint
The $count stage returns a document with the field name you specify and the count of documents passed to it.
✗ Incorrect
The pipeline first filters documents with status 'completed'. Then $count returns a single document with the field 'totalCompleted' and the number of matched documents. If there are 5 such documents, the output is [{ "totalCompleted": 5 }].
🧠 Conceptual
intermediate1:30remaining
Understanding $count accumulator behavior
What does the $count accumulator stage do in a MongoDB aggregation pipeline?
Attempts:
2 left
💡 Hint
Think about what $count outputs after processing all documents.
✗ Incorrect
$count counts how many documents it receives and outputs exactly one document with the count under the specified field name.
📝 Syntax
advanced2:00remaining
Identify the syntax error in $count usage
Which of the following aggregation pipelines will cause a syntax error due to incorrect $count usage?
Attempts:
2 left
💡 Hint
$count expects a string as its argument, not an object.
✗ Incorrect
The $count stage requires a string specifying the output field name. Option D passes an object, which is invalid syntax and causes an error.
❓ optimization
advanced2:30remaining
Optimizing count queries with $count
You want to count documents with a specific condition in a large MongoDB collection. Which pipeline is more efficient?
Attempts:
2 left
💡 Hint
Filtering early reduces the number of documents processed by $count.
✗ Incorrect
Option C filters documents first with $match, then counts only those matching. This reduces workload and is more efficient than grouping all documents or counting unrelated documents.
🔧 Debug
expert3:00remaining
Why does this $count pipeline return an empty array?
Consider this aggregation pipeline:
It returns an empty array []. Why?
[{ $match: { age: { $gt: 100 } } }, { $count: "oldPeople" }]It returns an empty array []. Why?
Attempts:
2 left
💡 Hint
Think about what happens if no documents pass the $match filter.
✗ Incorrect
If no documents match the $match condition, $count receives zero documents and returns an empty array instead of a document with count 0.