0
0
MongoDBquery~10 mins

$push accumulator for building arrays 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 use $push to add values to an array in aggregation.

MongoDB
db.collection.aggregate([{ $group: { _id: "$category", items: { [1]: "$item" } } }])
Drag options to blanks, or click blank then click option'
A$push
B$addToSet
C$sum
D$avg
Attempts:
3 left
💡 Hint
Common Mistakes
Using $sum or $avg instead of $push.
Confusing $push with $addToSet which avoids duplicates.
2fill in blank
medium

Complete the code to group documents by "type" and push "name" into an array.

MongoDB
db.products.aggregate([{ $group: { _id: "$type", names: { [1]: "$name" } } }])
Drag options to blanks, or click blank then click option'
A$push
B$max
C$sum
D$min
Attempts:
3 left
💡 Hint
Common Mistakes
Using $sum or $max which do not build arrays.
Forgetting to use $push inside $group.
3fill in blank
hard

Fix the error in the aggregation pipeline to correctly push "score" values into an array.

MongoDB
db.scores.aggregate([{ $group: { _id: "$player", scores: { [1]: "$score" } } }])
Drag options to blanks, or click blank then click option'
A$addToSet
B$avg
C$push
D$count
Attempts:
3 left
💡 Hint
Common Mistakes
Using $count which is not an accumulator for arrays.
Using $avg which calculates average instead of collecting values.
4fill in blank
hard

Fill both blanks to group by "department" and push "employee" names into an array.

MongoDB
db.employees.aggregate([{ $group: { _id: [1], staff: { [2]: "$employee" } } }])
Drag options to blanks, or click blank then click option'
A"$department"
B$push
C$sum
D"department"
Attempts:
3 left
💡 Hint
Common Mistakes
Using the field name without $ in _id.
Using $sum instead of $push for array building.
5fill in blank
hard

Fill all three blanks to group by "category", push "product" names, and filter only categories with more than 2 products.

MongoDB
db.products.aggregate([
  { $group: { _id: [1], products: { [2]: "$product" } } },
  { $match: { $expr: { $gt: [ { $[3]: "$products" }, 2 ] } } }
])
Drag options to blanks, or click blank then click option'
A"$category"
B$push
Clength
Dsize
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'length' instead of 'size' to check array length in $match.
Forgetting $ in the group _id field.