0
0
MongoDBquery~10 mins

Computed pattern for pre-aggregation in MongoDB - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to add a new field 'totalSales' that sums the 'amount' field in each document.

MongoDB
db.sales.aggregate([{ $addFields: { totalSales: { $[1]: "$amount" } } }])
Drag options to blanks, or click blank then click option'
Amin
Bavg
Cmax
Dsum
Attempts:
3 left
💡 Hint
Common Mistakes
Using $avg instead of $sum will calculate average, not total.
Using $max or $min will not sum values.
2fill in blank
medium

Complete the code to group documents by 'category' and calculate the total sales per category.

MongoDB
db.sales.aggregate([{ $group: { _id: "$category", total: { $[1]: "$amount" } } }])
Drag options to blanks, or click blank then click option'
Aavg
Bcount
Csum
Dmax
Attempts:
3 left
💡 Hint
Common Mistakes
Using $count inside $group is invalid for summing values.
Using $avg will calculate average, not total.
3fill in blank
hard

Fix the error in the aggregation pipeline to correctly compute the average 'score' per 'player'.

MongoDB
db.games.aggregate([{ $group: { _id: "$player", avgScore: { $[1]: "$score" } } }])
Drag options to blanks, or click blank then click option'
Aavg
Bsum
Cmax
Dmin
Attempts:
3 left
💡 Hint
Common Mistakes
Using $sum will give total, not average.
Using $max or $min will give wrong results.
4fill in blank
hard

Fill both blanks to create a pre-aggregation that groups by 'region' and counts the number of sales.

MongoDB
db.sales.aggregate([{ $group: { _id: "$ [1] ", count: { $[2]: 1 } } }])
Drag options to blanks, or click blank then click option'
Aregion
Bsum
Ccount
Dcategory
Attempts:
3 left
💡 Hint
Common Mistakes
Using $count inside $group is invalid.
Grouping by wrong field will give wrong groups.
5fill in blank
hard

Fill all three blanks to create a pre-aggregation pipeline that groups by 'product', calculates total 'quantity', and filters groups with total quantity greater than 100.

MongoDB
db.sales.aggregate([ { $group: { _id: "$ [1] ", totalQty: { $[2]: "$quantity" } } }, { $match: { totalQty: { $[3]: 100 } } } ])
Drag options to blanks, or click blank then click option'
Aproduct
Bsum
Cgt
Dcategory
Attempts:
3 left
💡 Hint
Common Mistakes
Using $avg instead of $sum will calculate average, not total.
Using $lt instead of $gt will filter wrong groups.