0
0
MongoDBquery~20 mins

$count accumulator in MongoDB - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
MongoDB $count Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2: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" }]
A[ { "totalCompleted": 5 } ]
B[ { "totalCompleted": 0 } ]
C[ { "count": 5 } ]
D[]
Attempts:
2 left
💡 Hint
The $count stage returns a document with the field name you specify and the count of documents passed to it.
🧠 Conceptual
intermediate
1:30remaining
Understanding $count accumulator behavior
What does the $count accumulator stage do in a MongoDB aggregation pipeline?
ACounts the number of fields in each document and outputs the count per document.
BCounts the number of documents input to it and outputs a single document with the count.
CCounts the number of distinct values of a specified field.
DCounts the total size in bytes of all documents passed to it.
Attempts:
2 left
💡 Hint
Think about what $count outputs after processing all documents.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in $count usage
Which of the following aggregation pipelines will cause a syntax error due to incorrect $count usage?
A[{ $count: "total" }]
B[{ $match: { status: "active" } }, { $count: "activeCount" }]
C[{ $group: { _id: null, count: { $sum: 1 } } }]
D[{ $count: { total: true } }]
Attempts:
2 left
💡 Hint
$count expects a string as its argument, not an object.
optimization
advanced
2: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?
A[{ $group: { _id: "$status", count: { $sum: 1 } } }, { $match: { _id: "pending" } }]
B[{ $project: { status: 1 } }, { $count: "count" }]
C[{ $match: { status: "pending" } }, { $count: "pendingCount" }]
D[{ $match: { status: { $exists: true } } }, { $count: "count" }]
Attempts:
2 left
💡 Hint
Filtering early reduces the number of documents processed by $count.
🔧 Debug
expert
3:00remaining
Why does this $count pipeline return an empty array?
Consider this aggregation pipeline:

[{ $match: { age: { $gt: 100 } } }, { $count: "oldPeople" }]

It returns an empty array []. Why?
ANo documents match the condition, so $count outputs no documents.
B$count always returns an empty array if used after $match.
CThe field name in $count must be _id, otherwise it returns empty.
DThe $match stage is invalid and filters out all documents.
Attempts:
2 left
💡 Hint
Think about what happens if no documents pass the $match filter.