Bird
Raised Fist0
MongoDBquery~20 mins

$first and $last accumulators in MongoDB - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
MongoDB $first and $last Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
What is the output of this MongoDB aggregation using $first?
Consider a collection named sales with documents:
{ "_id": 1, "item": "apple", "qty": 5, "date": ISODate("2023-01-01") }
{ "_id": 2, "item": "apple", "qty": 10, "date": ISODate("2023-01-02") }
{ "_id": 3, "item": "apple", "qty": 7, "date": ISODate("2023-01-03") }

What will be the result of this aggregation?
db.sales.aggregate([
  { $match: { item: "apple" } },
  { $sort: { date: 1 } },
  { $group: {
      _id: "$item",
      firstQty: { $first: "$qty" }
  } }
])
MongoDB
db.sales.aggregate([
  { $match: { item: "apple" } },
  { $sort: { date: 1 } },
  { $group: {
      _id: "$item",
      firstQty: { $first: "$qty" }
  } }
])
A[{ "_id": "apple", "firstQty": 5 }]
B[{ "_id": "apple", "firstQty": 7 }]
C[{ "_id": "apple", "firstQty": 10 }]
D[{ "_id": "apple", "firstQty": null }]
Attempts:
2 left
💡 Hint
Remember $first returns the value from the first document in the group after sorting.
❓ query_result
intermediate
2:00remaining
What does $last return in this aggregation?
Given the same sales collection as before, what is the output of:
db.sales.aggregate([
  { $match: { item: "apple" } },
  { $sort: { date: 1 } },
  { $group: {
      _id: "$item",
      lastQty: { $last: "$qty" }
  } }
])
MongoDB
db.sales.aggregate([
  { $match: { item: "apple" } },
  { $sort: { date: 1 } },
  { $group: {
      _id: "$item",
      lastQty: { $last: "$qty" }
  } }
])
A[{ "_id": "apple", "lastQty": 5 }]
B[{ "_id": "apple", "lastQty": 7 }]
C[{ "_id": "apple", "lastQty": 10 }]
D[{ "_id": "apple", "lastQty": null }]
Attempts:
2 left
💡 Hint
Think about the last document after sorting by date ascending.
📝 Syntax
advanced
2:00remaining
Which aggregation stage correctly uses $first to get the earliest date?
You want to group documents by category and get the earliest date for each group. Which option is correct?
A{ $group: { _id: "$category", earliestDate: { $first: "$dates" } } }
B{ $group: { _id: "$category", earliestDate: { $first: { $date: "$date" } } } }
C{ $group: { _id: "$category", earliestDate: { $first: "$category.date" } } }
D{ $group: { _id: "$category", earliestDate: { $first: "$date" } } }
Attempts:
2 left
💡 Hint
Use the field name directly inside $first after sorting.
🔧 Debug
advanced
2:00remaining
Why does this aggregation return null for $last?
Given this aggregation:
db.orders.aggregate([
  { $group: { _id: "$customer", lastOrder: { $last: "$orderDate" } } }
])

It returns lastOrder: null for all customers. Why?
MongoDB
db.orders.aggregate([
  { $group: { _id: "$customer", lastOrder: { $last: "$orderDate" } } }
])
ABecause the documents are not sorted before grouping, so $last returns the last document in an unordered group, which can be null.
BBecause the field name "orderDate" is misspelled or missing in documents.
CBecause $last only works on arrays, not on fields.
DBecause $last requires a $sort stage before $group to work correctly.
Attempts:
2 left
💡 Hint
Check if the field exists in the documents.
🧠 Conceptual
expert
2:00remaining
How do $first and $last behave without a $sort stage?
In a MongoDB aggregation pipeline, if you use $first and $last inside a $group stage without a preceding $sort, what determines the values returned?
A$first and $last return values from documents in the natural order of the input collection, which is undefined and may vary.
B$first and $last always return the earliest and latest values by date automatically.
C$first returns the minimum value and $last returns the maximum value of the grouped field.
D$first and $last cause an error if $sort is not used before $group.
Attempts:
2 left
💡 Hint
Think about how MongoDB processes documents without explicit sorting.

Practice

(1/5)
1. What does the $first accumulator do in a MongoDB aggregation pipeline?
easy
A. It returns the last value of a specified field in each group.
B. It counts the number of documents in each group.
C. It sorts the documents in ascending order.
D. It returns the first value of a specified field in each group.

Solution

  1. Step 1: Understand the role of $first

    The $first accumulator returns the first value of a specified field from documents in a group.
  2. Step 2: Differentiate from other accumulators

    Unlike $last, which returns the last value, $first picks the earliest value based on the document order.
  3. Final Answer:

    It returns the first value of a specified field in each group. -> Option D
  4. Quick Check:

    $first = first value [OK]
Hint: Remember: $first picks earliest value in group [OK]
Common Mistakes:
  • Confusing $first with $last accumulator
  • Thinking $first sorts documents automatically
  • Assuming $first counts documents
2. Which of the following is the correct syntax to use $last in a MongoDB aggregation $group stage?
easy
A. { $group: { _id: "$category", lastItem: { last: "$item" } } }
B. { $group: { _id: "$category", lastItem: { $first: "$item" } } }
C. { $group: { _id: "$category", lastItem: { $last: "$item" } } }
D. { $group: { _id: "$category", lastItem: { $last: item } } }

Solution

  1. Step 1: Identify correct accumulator usage

    The $last accumulator must be used with a field path as a string, like "$item".
  2. Step 2: Check syntax correctness

    { $group: { _id: "$category", lastItem: { $last: "$item" } } } correctly uses $last: "$item" inside $group. Options A and C have syntax errors, and B uses $first instead of $last.
  3. Final Answer:

    { $group: { _id: "$category", lastItem: { $last: "$item" } } } -> Option C
  4. Quick Check:

    Correct $last syntax = { $group: { _id: "$category", lastItem: { $last: "$item" } } } [OK]
Hint: Use $last with field path as string "$field" [OK]
Common Mistakes:
  • Omitting quotes around field name
  • Using $first instead of $last by mistake
  • Writing accumulator name incorrectly
3. Given the collection sales with documents:
{ "_id": 1, "product": "A", "date": "2023-01-01" },
{ "_id": 2, "product": "A", "date": "2023-01-05" },
{ "_id": 3, "product": "B", "date": "2023-01-02" }

What will be the output of this aggregation?
[
  { $sort: { date: 1 } },
  { $group: { _id: "$product", firstSale: { $first: "$date" }, lastSale: { $last: "$date" } } }
]
medium
A. [{ "_id": "A", "firstSale": "2023-01-05", "lastSale": "2023-01-01" }, { "_id": "B", "firstSale": "2023-01-02", "lastSale": "2023-01-02" }]
B. [{ "_id": "A", "firstSale": "2023-01-01", "lastSale": "2023-01-05" }, { "_id": "B", "firstSale": "2023-01-02", "lastSale": "2023-01-02" }]
C. [{ "_id": "A", "firstSale": "2023-01-01", "lastSale": "2023-01-01" }, { "_id": "B", "firstSale": "2023-01-02", "lastSale": "2023-01-02" }]
D. [{ "_id": "A", "firstSale": null, "lastSale": null }, { "_id": "B", "firstSale": null, "lastSale": null }]

Solution

  1. Step 1: Sort documents by date ascending

    The $sort stage orders documents by date: A on 2023-01-01, B on 2023-01-02, A on 2023-01-05.
  2. Step 2: Group by product and apply $first and $last

    For product A, firstSale is earliest date "2023-01-01", lastSale is latest date "2023-01-05". For B, both firstSale and lastSale are "2023-01-02".
  3. Final Answer:

    [{ "_id": "A", "firstSale": "2023-01-01", "lastSale": "2023-01-05" }, { "_id": "B", "firstSale": "2023-01-02", "lastSale": "2023-01-02" }] -> Option B
  4. Quick Check:

    Sorted + grouped $first/$last = [{ "_id": "A", "firstSale": "2023-01-01", "lastSale": "2023-01-05" }, { "_id": "B", "firstSale": "2023-01-02", "lastSale": "2023-01-02" }] [OK]
Hint: Sort first, then $first/$last pick earliest/latest values [OK]
Common Mistakes:
  • Ignoring $sort stage before $group
  • Mixing up $first and $last values
  • Assuming $first/$last pick random values
4. You wrote this aggregation but it returns incorrect $last values:
db.orders.aggregate([
  { $group: { _id: "$customer", lastOrder: { $last: "$orderDate" } } }
])

What is the most likely reason?
medium
A. You forgot to sort documents by orderDate before grouping.
B. You used $last instead of $first.
C. The orderDate field is missing in documents.
D. You need to use $max instead of $last.

Solution

  1. Step 1: Understand $last depends on document order

    The $last accumulator returns the last value in the current document order within each group.
  2. Step 2: Identify missing $sort stage

    Without sorting by orderDate, documents are in arbitrary order, so $last may not return the latest date.
  3. Final Answer:

    You forgot to sort documents by orderDate before grouping. -> Option A
  4. Quick Check:

    Missing $sort before $group causes wrong $last [OK]
Hint: Always $sort by date before using $last [OK]
Common Mistakes:
  • Assuming $last finds max value automatically
  • Using $last without sorting documents
  • Confusing $last with $max accumulator
5. You have a collection events with documents:
{ "user": "Alice", "timestamp": 100 },
{ "user": "Alice", "timestamp": 200 },
{ "user": "Bob", "timestamp": 150 },
{ "user": "Bob", "timestamp": 50 }

You want to find each user's first and last event timestamps using the $first and $last accumulators. Which aggregation pipeline correctly achieves this?
hard
A. [ { $sort: { timestamp: 1 } }, { $group: { _id: "$user", firstEvent: { $first: "$timestamp" }, lastEvent: { $last: "$timestamp" } } } ]
B. [ { $group: { _id: "$user", firstEvent: { $first: "$timestamp" }, lastEvent: { $last: "$timestamp" } } } ]
C. [ { $sort: { timestamp: -1 } }, { $group: { _id: "$user", firstEvent: { $first: "$timestamp" }, lastEvent: { $last: "$timestamp" } } } ]
D. [ { $group: { _id: "$user", firstEvent: { $min: "$timestamp" }, lastEvent: { $max: "$timestamp" } } } ]

Solution

  1. Step 1: Sort events by timestamp ascending

    Sorting by timestamp: 1 ensures earliest events come first for each user.
  2. Step 2: Group by user and use $first and $last

    Using $first and $last after sorting picks the earliest and latest timestamps correctly.
  3. Final Answer:

    [ { $sort: { timestamp: 1 } }, { $group: { _id: "$user", firstEvent: { $first: "$timestamp" }, lastEvent: { $last: "$timestamp" } } } ] -> Option A
  4. Quick Check:

    Sort ascending + $first/$last = [ { $sort: { timestamp: 1 } }, { $group: { _id: "$user", firstEvent: { $first: "$timestamp" }, lastEvent: { $last: "$timestamp" } } } ] [OK]
Hint: Sort ascending before grouping to get correct first/last [OK]
Common Mistakes:
  • Skipping $sort stage before $group
  • Sorting descending when $first expects ascending
  • Using $min/$max instead of $first/$last when order matters
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