Bird
Raised Fist0
MongoDBquery~20 mins

Computed pattern for pre-aggregation in MongoDB - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
MongoDB Pre-Aggregation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
Output of a pre-aggregation computed field
Given a MongoDB collection sales with documents containing price and quantity, what is the output of this aggregation pipeline?
MongoDB
db.sales.aggregate([
  {
    $project: {
      totalSale: { $multiply: ["$price", "$quantity"] },
      item: 1
    }
  }
])
A[{ "item": "apple", "totalSale": null }, { "item": "banana", "totalSale": null }]
B[{ "item": "apple", "totalSale": 3 }, { "item": "banana", "totalSale": 2 }]
C[{ "item": "apple", "totalSale": 30 }, { "item": "banana", "totalSale": 20 }]
D[{ "item": "apple", "totalSale": "30" }, { "item": "banana", "totalSale": "20" }]
Attempts:
2 left
💡 Hint
Remember that $multiply computes the product of numeric fields.
📝 Syntax
intermediate
1:30remaining
Identify the syntax error in computed pre-aggregation
Which option contains a syntax error in the MongoDB aggregation pipeline that computes a new field?
MongoDB
db.orders.aggregate([
  {
    $project: {
      total: { $add: ["$price", "$tax"] },
      item: 1
    }
  }
])
ANo syntax error; the pipeline is correct
BMissing comma between fields inside $project
CField names must not be quoted inside $add
DUsing $add with an array is invalid syntax
Attempts:
2 left
💡 Hint
Check the use of $add operator and field quoting.
❓ optimization
advanced
2:30remaining
Optimize pre-aggregation for repeated computed fields
You want to optimize a MongoDB aggregation pipeline that computes the same complex field multiple times. Which approach is best?
AUse $group to compute the field multiple times
BCompute the field once in a $addFields stage and reuse it later
CRepeat the computation in every $project stage where needed
DStore the computed field in the original documents manually
Attempts:
2 left
💡 Hint
Avoid repeating expensive computations in multiple stages.
🔧 Debug
advanced
2:00remaining
Debug incorrect computed field in pre-aggregation
Why does this pipeline produce null for the computed field totalCost?
MongoDB
db.products.aggregate([
  {
    $project: {
      totalCost: { $multiply: ["$cost", "$quantity"] },
      name: 1
    }
  }
])
AField names cost and quantity do not exist in documents
BUsing $multiply with strings causes null output
CMissing $match stage before $project
DIncorrect use of $project operator
Attempts:
2 left
💡 Hint
Check if the fields used in $multiply exist in the documents.
🧠 Conceptual
expert
3:00remaining
Understanding computed pattern for pre-aggregation in MongoDB
Which statement best describes the computed pattern for pre-aggregation in MongoDB?
AIt only works with $group stages and cannot use $project or $addFields
BIt requires storing all computed fields permanently in the database documents
CIt uses map-reduce exclusively to compute aggregated values
DIt involves computing derived fields during aggregation to avoid repeated calculations later
Attempts:
2 left
💡 Hint
Think about how computed fields help with performance in aggregation pipelines.

Practice

(1/5)
1. What is the main purpose of using a computed pattern for pre-aggregation in MongoDB?
easy
A. To delete all raw data after aggregation
B. To create indexes on every field automatically
C. To calculate and store summary data ahead of time for faster queries
D. To replicate data across multiple servers

Solution

  1. Step 1: Understand pre-aggregation concept

    Pre-aggregation means computing summary data before queries run, so queries are faster.
  2. Step 2: Identify the main goal

    The goal is to store computed summaries to avoid recalculating on every query.
  3. Final Answer:

    To calculate and store summary data ahead of time for faster queries -> Option C
  4. Quick Check:

    Pre-aggregation = faster queries [OK]
Hint: Pre-aggregation means compute summaries before queries [OK]
Common Mistakes:
  • Confusing pre-aggregation with data deletion
  • Thinking it automatically creates indexes
  • Mixing it with data replication
2. Which MongoDB aggregation stage is primarily used to compute grouped summary data for pre-aggregation?
easy
A. $match
B. $group
C. $project
D. $sort

Solution

  1. Step 1: Recall aggregation stages

    $group is used to group documents and compute summary values like sums or counts.
  2. Step 2: Identify correct stage for pre-aggregation

    Pre-aggregation requires grouping and computing, so $group is the right stage.
  3. Final Answer:

    $group -> Option B
  4. Quick Check:

    $group = grouping and computing summaries [OK]
Hint: Use $group to compute grouped summaries [OK]
Common Mistakes:
  • Choosing $match which filters but does not compute
  • Confusing $project with grouping
  • Selecting $sort which only orders data
3. Given the following aggregation pipeline, what will be the output?
[{ $group: { _id: "$category", total: { $sum: "$amount" } } }]
Assuming the collection has documents: {category: "A", amount: 10}, {category: "B", amount: 5}, {category: "A", amount: 15}.
medium
A. [{_id: null, total: 30}]
B. [{_id: "A", total: 10}, {_id: "B", total: 5}, {_id: "A", total: 15}]
C. [{_id: "A", total: 15}, {_id: "B", total: 5}]
D. [{_id: "A", total: 25}, {_id: "B", total: 5}]

Solution

  1. Step 1: Group documents by category

    Documents with category "A" are grouped together, and category "B" separately.
  2. Step 2: Sum amounts per group

    For "A": 10 + 15 = 25; for "B": 5.
  3. Final Answer:

    [{_id: "A", total: 25}, {_id: "B", total: 5}] -> Option D
  4. Quick Check:

    Sum amounts by category = correct totals [OK]
Hint: Sum amounts grouped by _id field [OK]
Common Mistakes:
  • Not grouping sums correctly
  • Returning individual documents instead of grouped
  • Using null _id which sums all documents
4. Identify the error in this aggregation pipeline for pre-aggregation:
[{ $group: { _id: "$category", total: { $sum: "amount" } } }]
medium
A. Missing $ before amount in $sum operator
B. Incorrect use of $group stage
C. Missing $match stage before $group
D. Using _id field incorrectly

Solution

  1. Step 1: Check $sum operator syntax

    $sum requires a field path starting with $, but "amount" is missing the $.
  2. Step 2: Confirm correct syntax

    It should be $sum: "$amount" to sum the amount field values.
  3. Final Answer:

    Missing $ before amount in $sum operator -> Option A
  4. Quick Check:

    $sum needs $field syntax [OK]
Hint: Field names in aggregation need $ prefix [OK]
Common Mistakes:
  • Forgetting $ before field names in operators
  • Assuming $match is mandatory before $group
  • Misusing _id field in $group
5. You want to pre-aggregate sales data by month and product category, storing total sales and average price. Which aggregation pipeline correctly computes these values?
hard
A. [{ $group: { _id: { month: { $month: "$date" }, category: "$category" }, totalSales: { $sum: "$amount" }, avgPrice: { $avg: "$price" } } }]
B. [{ $group: { _id: "$date", totalSales: { $sum: "$amount" }, avgPrice: { $avg: "$price" } } }]
C. [{ $group: { _id: { month: "$date", category: "$category" }, totalSales: { $sum: "$amount" }, avgPrice: { $avg: "$price" } } }]
D. [{ $group: { _id: { month: { $month: "$date" }, category: "$category" }, totalSales: { $sum: "$price" }, avgPrice: { $avg: "$amount" } } }]

Solution

  1. Step 1: Group by month and category correctly

    Use $month operator on "$date" to extract month, and include "$category" as second key.
  2. Step 2: Compute total sales and average price correctly

    Sum the "$amount" field for totalSales and average the "$price" field for avgPrice.
  3. Final Answer:

    [{ $group: { _id: { month: { $month: "$date" }, category: "$category" }, totalSales: { $sum: "$amount" }, avgPrice: { $avg: "$price" } } }] -> Option A
  4. Quick Check:

    Group by month+category, sum amount, avg price [OK]
Hint: Use $month for date grouping and correct fields for sum/avg [OK]
Common Mistakes:
  • Grouping by full date instead of month
  • Swapping sum and avg fields
  • Not using $month operator for month extraction
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