0
0
MongoDBquery~10 mins

$first and $last accumulators 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 get the first document's name in each group.

MongoDB
{ $group: { _id: "$category", firstName: { [1]: "$name" } } }
Drag options to blanks, or click blank then click option'
A$first
B$sum
C$last
D$avg
Attempts:
3 left
💡 Hint
Common Mistakes
Using $last instead of $first will return the last document's value.
Using $sum or $avg will cause errors or unexpected results.
2fill in blank
medium

Complete the code to get the last document's score in each group.

MongoDB
{ $group: { _id: "$team", lastScore: { [1]: "$score" } } }
Drag options to blanks, or click blank then click option'
A$min
B$last
C$max
D$first
Attempts:
3 left
💡 Hint
Common Mistakes
Using $first will return the first document's value, not the last.
Using $max or $min will return the maximum or minimum values, not the last.
3fill in blank
hard

Fix the error in the aggregation pipeline to correctly get the first and last names.

MongoDB
[ { $group: { _id: "$department", firstEmp: { [1]: "$employee" }, lastEmp: { $last: "$employee" } } } ]
Drag options to blanks, or click blank then click option'
A$first
B$sum
C$max
D$avg
Attempts:
3 left
💡 Hint
Common Mistakes
Using $sum or $avg causes errors because they are not valid for string fields.
Using $max returns the maximum value, not the first.
4fill in blank
hard

Fill both blanks to get the first and last order dates for each customer.

MongoDB
{ $group: { _id: "$customerId", firstOrder: { [1]: "$orderDate" }, lastOrder: { [2]: "$orderDate" } } }
Drag options to blanks, or click blank then click option'
A$first
B$last
C$max
D$min
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping $first and $last will give incorrect results.
Using $max or $min will return the highest or lowest dates, not the first or last.
5fill in blank
hard

Fill all three blanks to get the first product name, last product name, and maximum price in each category.

MongoDB
{ $group: { _id: "$category", firstProduct: { [1]: "$productName" }, lastProduct: { [2]: "$productName" }, maxPrice: { [3]: "$price" } } }
Drag options to blanks, or click blank then click option'
A$first
B$last
C$max
D$min
Attempts:
3 left
💡 Hint
Common Mistakes
Using $min instead of $max for price will give the lowest price, not the highest.
Mixing up $first and $last will swap the product names incorrectly.