27. Practice Exercises and Challenge Problems
Exercise 1: Status distribution
Count orders in each status and sort by frequency. Skills: $group, $sum, $sort.
Exercise 2: Customer spending
Calculate delivered item revenue per customer. Create one version excluding discounts and another subtracting each order-level discount once. Skills: $reduce, $group, business rules.
Exercise 3: Product units sold
Calculate quantity sold per product and return the top three. Skills: $match, $unwind, $group, $sort, $limit.
Exercise 4: Monthly order counts
Group by month and year, then compare all statuses with delivered-only orders. Skills: $dateTrunc, $group.
Exercise 5: Customer category diversity
Count distinct categories purchased by each customer and return customers with at least two categories. Skills: $addToSet, $size, $match.
Exercise 6: Product dashboard
Use $facet to return a product list, category counts, and total count.
Exercise 7: Data-quality audit
Convert imported amounts to Decimal128 and count valid and invalid values.
Exercise 8: Top customer per city
Join orders to customers, calculate delivered revenue, and find the highest-spending customer in each city. Define tie handling.
Exercise 9: Moving average
Calculate a moving average over the current and two preceding orders per customer using $setWindowFields.
Exercise 10: Materialized report
Write product summaries to a reporting collection, run the pipeline twice, and verify idempotency and stale-record handling.
Challenge: Explain the cost
Compare execution statistics before and after an appropriate index or pipeline rewrite using realistic data. Report only measured performance changes.
- Practice each stage independently.
- Define discount and shipping rules explicitly.
- Test missing arrays and malformed values.
- Verify write-pipeline repeatability.
- Use explain output and benchmarks.
How do you calculate a quantity-weighted average unit price?