The $lastN accumulator collects the last N input values from each $group bucket—ideal for the three most recent orders per customer, latest events, or trailing scores when you define order with $sort.
01
N values per group
Array of trailing records.
02
input + n
Two required properties.
03
Needs $sort
Order before $group matters.
04
vs $last
Many values vs one value.
05
vs $bottomN
Pre-sorted vs in-group rank.
06
Array operator too
Slice array tails in $project.
Fundamentals
Definition and Usage
$lastN is a MongoDB accumulator used in the $group stage. For each group, it evaluates an input expression on the last n documents (in pipeline order) and returns those values as an array.
💡
Beginner tip
$lastN does not sort documents. It takes the final N docs that reach each group. Add $sort before $group when you need the three latest dates, most recent statuses, or lowest scores at the tail of a descending sort.
Use $lastN when the stream is already ordered. If MongoDB should rank inside the group, consider $bottomN instead. For a single trailing value, use $last.
Foundation
📝 Syntax
As a $group accumulator, $lastN requires input and n:
$lastN extends $last to collect several trailing values per group. Pair it with $sort, set input and n, and you get clean recent-N or tail-N reports without manual array slicing.
Need only one value? Use $last. Need in-group ranking? Try $bottomN. Next up: $max for peak values across a group.
Add $sort before $group whenever order defines “last”
Include tie-break sort keys (_id, timestamp) for stable tail arrays
Use tuple input: ["$player", "$score"] for compact recent-record rows
Test groups smaller than n to confirm array length behavior
Use the array-operator form to slice tails of embedded array fields
❌ Don’t
Confuse $lastN with $last (array vs single value)
Skip $sort and expect consistent “latest N” results
Use $lastN when $bottomN in-group ranking is clearer
Assume null/missing values are skipped—they are included in the array
Deploy on MongoDB versions before 5.2 without a fallback pipeline
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about $lastN
Use these points when building last-N lists inside $group.
5
Core concepts
📦01
Array of N
Trailing values per group.
Basics
📄02
input + n
Two required keys.
Syntax
📅03
$sort first
Define what last means.
Pattern
👤04
vs $last
List vs single value.
Compare
⬇️05
vs $bottomN
Pre-sort vs in-group rank.
Choose
❓ Frequently Asked Questions
$lastN returns an array of the last N input values from each $group bucket—based on the order documents arrive at $group. Use it for the three most recent orders per customer, latest N events, or trailing scores when you control order with $sort.
Inside $group: { lastThree: { $lastN: { input: "$score", n: 3 } } }. Both input and n are required. It also works as an array operator in $project and $addFields to slice the last N elements from an array field.
Yes, whenever order matters. $lastN collects the last N documents as they enter each group—it does not sort for you. Add $sort before $group so last means latest, most recent, or trailing per your rules.
$last returns one value from the final document. $lastN returns an array of up to N values from the last N documents. Use $last for a single trailing field; use $lastN for a list of recent records.
$lastN assumes documents are already ordered (usually via $sort). $bottomN sorts inside $group with sortBy and picks the bottom N. Use $lastN when you sorted upstream; use $bottomN when ranking happens in the accumulator.
$lastN returns all available elements—never more than exist in the group. A group with two documents and n: 3 yields an array of two items.
Did you know?
MongoDB docs note that $lastN and $bottomN can produce similar results—use $lastN when documents are already sorted, and $bottomN when ranking should happen inside $group. $lastN also works as an array expression; $bottomN does not. See the official $lastN docs.