Bird
Raised Fist0
MongoDBquery~20 mins

Aggregation for reporting dashboards in MongoDB - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Aggregation Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
Calculate total sales per product category
Given a MongoDB collection sales with documents containing category and amount fields, which aggregation pipeline produces the total sales amount for each category?
MongoDB
db.sales.aggregate([
  { $group: { _id: "$category", totalSales: { $sum: "$amount" } } }
])
A[{ $group: { _id: "$category", totalSales: { $max: "$amount" } } }]
B[{ $match: { amount: { $gt: 0 } } }, { $group: { _id: "$category", totalSales: { $avg: "$amount" } } }]
C[{ $group: { _id: "$category", totalSales: { $sum: "$amount" } } }]
D[{ $project: { category: 1, totalSales: { $sum: "$amount" } } }]
Attempts:
2 left
💡 Hint
Use $group to aggregate data by category and $sum to add amounts.
❓ query_result
intermediate
2:00remaining
Filter and count orders above threshold
Which aggregation pipeline returns the count of orders with totalPrice greater than 100 in the orders collection?
MongoDB
db.orders.aggregate([
  { $match: { totalPrice: { $gt: 100 } } },
  { $count: "highValueOrders" }
])
A[{ $match: { totalPrice: { $gt: 100 } } }, { $count: "highValueOrders" }]
B[{ $match: { totalPrice: { $gte: 100 } } }, { $count: "highValueOrders" }]
C[{ $group: { _id: null, count: { $sum: 1 } } }, { $match: { totalPrice: { $gt: 100 } } }]
D[{ $project: { highValue: { $gt: ["$totalPrice", 100] } } }, { $count: "highValueOrders" }]
Attempts:
2 left
💡 Hint
Filter first, then count the matching documents.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in this aggregation pipeline
Which option contains a syntax error that will cause the MongoDB aggregation to fail?
MongoDB
db.users.aggregate([
  { $group: { _id: "$city", totalUsers: { $sum: 1 } } },
  { $sort: { totalUsers: -1 } }
])
A[{ $group: { _id: "$city", totalUsers: { $sum: 1 } } }, { $sort: { totalUsers: -1 } }]
B[{ $group: { _id: "$city", totalUsers: { $sum: 1 } } }, { $sort: { totalUsers: "desc" } }]
C[{ $group: { _id: "$city", totalUsers: { $sum: 1 } } }, { $sort: { totalUsers: 1 } }]
D[{ $group: { _id: "$city", totalUsers: { $sum: 1 } } }, { $sort: { totalUsers: 0 } }]
Attempts:
2 left
💡 Hint
Check the value used for sorting order in $sort stage.
❓ optimization
advanced
2:00remaining
Optimize aggregation pipeline for large datasets
You want to calculate the average rating per product from a large reviews collection. Which pipeline is the most efficient?
A[{ $project: { productId: 1, rating: 1 } }, { $group: { _id: "$productId", avgRating: { $avg: "$rating" } } }]
B[{ $group: { _id: "$productId", avgRating: { $avg: "$rating" } } }, { $match: { avgRating: { $gte: 4 } } }]
C[{ $group: { _id: "$productId", avgRating: { $avg: "$rating" } } }]
D[{ $match: { rating: { $exists: true } } }, { $group: { _id: "$productId", avgRating: { $avg: "$rating" } } }]
Attempts:
2 left
💡 Hint
Filter out documents missing rating before grouping to reduce workload.
🧠 Conceptual
expert
2:00remaining
Understanding $facet stage for dashboard reports
Which option best describes the purpose of the $facet stage in MongoDB aggregation pipelines for reporting dashboards?
AIt allows running multiple aggregation pipelines in parallel and returns their results in a single document.
BIt filters documents based on multiple conditions combined with AND logic.
CIt sorts documents by multiple fields in a single stage.
DIt groups documents by multiple fields and calculates sums for each.
Attempts:
2 left
💡 Hint
Think about how to get different summaries in one query.

Practice

(1/5)
1. What is the main purpose of using the $group stage in a MongoDB aggregation pipeline for reporting dashboards?
easy
A. To add new fields to documents without changing existing ones
B. To combine documents and calculate summary values like totals or averages
C. To sort documents in ascending or descending order
D. To filter documents based on specific conditions

Solution

  1. Step 1: Understand the role of $group

    The $group stage collects documents into groups and calculates summary statistics like sums or averages.
  2. Step 2: Compare with other stages

    $match filters, $sort orders, and $addFields adds fields, but only $group aggregates data.
  3. Final Answer:

    To combine documents and calculate summary values like totals or averages -> Option B
  4. Quick Check:

    $group = summary aggregation [OK]
Hint: Remember $group is for summarizing data by categories [OK]
Common Mistakes:
  • Confusing $group with $match filtering
  • Thinking $group sorts data
  • Assuming $group adds fields without aggregation
2. Which of the following is the correct syntax to start an aggregation pipeline in MongoDB?
easy
A. db.collection.aggregate([{ $match: { status: 'active' } }])
B. db.collection.find({ $match: { status: 'active' } })
C. db.collection.group({ status: 'active' })
D. db.collection.aggregateMatch({ status: 'active' })

Solution

  1. Step 1: Identify the aggregation method

    The correct method to start aggregation is aggregate() with an array of stages.
  2. Step 2: Check syntax correctness

    db.collection.aggregate([{ $match: { status: 'active' } }]) is valid; others use wrong methods or syntax.
  3. Final Answer:

    db.collection.aggregate([{ $match: { status: 'active' } }]) -> Option A
  4. Quick Check:

    aggregate() starts pipeline [OK]
Hint: Use aggregate() with an array of stages to start [OK]
Common Mistakes:
  • Using find() instead of aggregate() for pipelines
  • Trying to use group() as a method
  • Incorrect method names like aggregateMatch()
3. Given the collection sales with documents like { product: 'A', quantity: 5 } and { product: 'B', quantity: 3 }, what will this aggregation return?
db.sales.aggregate([
  { $group: { _id: '$product', totalQuantity: { $sum: '$quantity' } } },
  { $sort: { totalQuantity: -1 } }
])
medium
A. [{ _id: 'A', totalQuantity: 8 }]
B. [{ _id: 'B', totalQuantity: 3 }, { _id: 'A', totalQuantity: 5 }]
C. [{ _id: 'A', totalQuantity: 5 }, { _id: 'B', totalQuantity: 3 }]
D. SyntaxError due to missing fields

Solution

  1. Step 1: Group by product and sum quantity

    The $group stage groups documents by product and sums their quantities: 'A' -> 5, 'B' -> 3.
  2. Step 2: Sort by totalQuantity descending

    The $sort orders results by totalQuantity descending, so 'A' (5) comes before 'B' (3).
  3. Final Answer:

    [{ _id: 'A', totalQuantity: 5 }, { _id: 'B', totalQuantity: 3 }] -> Option C
  4. Quick Check:

    Group sums then sort desc = correct order [OK]
Hint: Group sums then sort descending by total [OK]
Common Mistakes:
  • Mixing up sort order ascending vs descending
  • Expecting combined total instead of grouped sums
  • Thinking syntax error occurs
4. Identify the error in this aggregation pipeline:
db.orders.aggregate([
  { $match: { status: 'completed' } },
  { $group: { _id: '$customerId', total: { $sum: '$amount' } } },
  { $sort: { total: 1 } },
  { $project: { customerId: 1, total: 1 } }
])
medium
A. The $sort stage must come before $group
B. The $sum operator cannot be used inside $group
C. The $match stage should be after $group
D. The $project stage uses a field not present in the grouped output

Solution

  1. Step 1: Check fields after $group

    After grouping by _id: '$customerId', the output fields are _id and total. The original customerId field is renamed to _id.
  2. Step 2: Analyze $project stage

    The $project tries to include customerId, which does not exist; it should use _id instead.
  3. Final Answer:

    The $project stage uses a field not present in the grouped output -> Option D
  4. Quick Check:

    Use _id after $group, not original field [OK]
Hint: After $group, use _id field names in $project [OK]
Common Mistakes:
  • Assuming original fields remain after $group
  • Placing $sort before $group incorrectly
  • Misusing $sum outside $group
5. You want to create a dashboard showing the average order amount per customer, but only for customers with more than 3 orders. Which aggregation pipeline correctly achieves this?
hard
A. [{ $group: { _id: '$customerId', avgAmount: { $avg: '$amount' }, count: { $sum: 1 } } }, { $match: { count: { $gt: 3 } } }]
B. [{ $match: { count: { $gt: 3 } } }, { $group: { _id: '$customerId', avgAmount: { $avg: '$amount' } } }]
C. [{ $group: { _id: '$customerId', avgAmount: { $avg: '$amount' } } }, { $match: { avgAmount: { $gt: 3 } } }]
D. [{ $group: { _id: '$customerId', avgAmount: { $avg: '$amount' } } }, { $sort: { avgAmount: -1 } }]

Solution

  1. Step 1: Group by customer and calculate average and count

    Use $group to get average order amount and count of orders per customer.
  2. Step 2: Filter customers with more than 3 orders

    Apply $match after grouping to keep only customers where count > 3.
  3. Final Answer:

    [{ $group: { _id: '$customerId', avgAmount: { $avg: '$amount' }, count: { $sum: 1 } } }, { $match: { count: { $gt: 3 } } }] -> Option A
  4. Quick Check:

    Group then filter by count > 3 [OK]
Hint: Filter after grouping to use aggregated counts [OK]
Common Mistakes:
  • Filtering by count before grouping
  • Filtering by avgAmount instead of count
  • Missing count calculation in $group
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard