MongoDB $lastN Accumulator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $lastN?

$lastN is a MongoDB accumulator for the $group stage (MongoDB 5.2+). For each group it returns an array of the last N input values—in the order documents arrive at $group.

Remember
$lastN = last N values per group (as an array)

input → expression to collect (e.g. "$product")
n     → how many to keep (positive integer)

Order comes from documents entering $group
→ $sort first when “last” must mean latest / cheapest
vs $last → one value; $lastN → up to N values
UsePrefer
Last N values after you sorted$lastN
Only the last single value$last
Rank bottom N inside $group$bottomN

How to Use $lastN in MongoDB

Two keys drive every call: input and n.

  1. Optionally $sort so documents enter $group in the order you want.
  2. Put $lastN inside $group on an output field.
  3. Set input to the field or expression to collect.
  4. Set n to how many trailing values to keep.
KeyRequired?Role
inputYesExpression to take from each document
nYesPositive integer (or expression based on group key)
$group._idYesGroup key ("$store", null, …)

Pseudocode

Pseudocode
// optional but recommended when order matters:
documents = sort(documents, sortSpec)

for each group:
    result = []
    for each document in group (arrival order):
        result.append(evaluate(input))
        if result.length > n:
            result.removeFirst()   // keep only the trailing n
    emit { _id: groupKey, field: result }

Cheat Sheet

Keep these facts handy while collecting the last N values.

TopicDetail
Stage$group accumulator (also array / expression form)
Syntax{ $lastN: { input: "$field", n: 3 } }
ReturnsArray of up to n values
OrderDocument arrival order—use $sort first
Short groupsFewer than n docs → return all of them
VersionMongoDB 5.2+

Live Preview

Watch the last 2 products per store after sorting by amount descending. Sample: A/Laptop 1200, A/Mouse 25, A/Keyboard 75, A/Monitor 300, B/Laptop 1100, B/Headset 80.

Simulates $sort by amount descending, then $lastN with n: 2 on product.

Result
store A after sort (amount ↓): Laptop, Monitor, Keyboard, Mouse
  → last 2 = ["Keyboard", "Mouse"]
store B after sort (amount ↓): Laptop, Headset
  → last 2 = ["Laptop", "Headset"]

[
  { _id: "A", lastProducts: ["Keyboard", "Mouse"] },
  { _id: "B", lastProducts: ["Laptop", "Headset"] }
]

Worked Walkthrough — Last 2 by Amount

Six orders, two stores. Sort by amount high to low, then keep the last two product names per store (the cheapest after that sort).

Calculation
Documents (before sort):
  A: Laptop 1200, Mouse 25, Keyboard 75, Monitor 300
  B: Laptop 1100, Headset 80

$sort: { amount: -1 }

store "A" arrival order:
  Laptop, Monitor, Keyboard, Mouse
  $lastN n:2 → ["Keyboard", "Mouse"]

store "B" arrival order:
  Laptop, Headset
  $lastN n:2 → ["Laptop", "Headset"]

Output:
  { _id: "A", lastProducts: ["Keyboard", "Mouse"] }
  { _id: "B", lastProducts: ["Laptop", "Headset"] }

MongoDB Examples

We use a tiny orders list. First we take the last two products in document order. Then we $sort by amount and take the last two again. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine six orders across stores A and B. Each document has a store, product, and amount.

mongosh
db.orders.insertMany([
  { store: "A", product: "Laptop", amount: 1200 },
  { store: "A", product: "Mouse", amount: 25 },
  { store: "A", product: "Keyboard", amount: 75 },
  { store: "A", product: "Monitor", amount: 300 },
  { store: "B", product: "Laptop", amount: 1100 },
  { store: "B", product: "Headset", amount: 80 }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps 6 documents in orders. Run find() to see them:

mongosh
db.orders.find()

Read each document like this:

Field in MongoDBMeaningExample
storeWhich store"A"
productWhat was sold"Monitor"
amountOrder amount300
Picture
Store A order stream (as inserted):
  Laptop, Mouse, Keyboard, Monitor

Next: $lastN keeps the last N values in that order.

How It Works

  1. Insert once. The sample command adds 6 documents to orders.
  2. MongoDB stores fields as written. Each document keeps the same field names and values you inserted.
  3. find() shows the same shape. What you inserted is what you get back—ready for $lastN in the next examples.

Example 2 — Last 2 in Document Order

Goal: for each store, keep the last two product values as they appear in the collection (no sort). Store A has four orders, so we only keep the trailing two.

mongosh
db.orders.aggregate([
  {
    $group: {
      _id: "$store",
      lastProducts: {
        $lastN: {
          input: "$product",
          n: 2
        }
      }
    }
  },
  { $sort: { _id: 1 } }
]);

How It Works

  1. Split by store. _id: "$store" makes groups "A" and "B".
  2. Read product names. input: "$product" is what gets pushed into the result array.
  3. Keep only the trailing n. With n: 2, store A keeps Keyboard and Monitor (drops Laptop and Mouse).
  4. Short groups are fine. Store B only has two orders, so both products appear.
  5. Need one value only? Use $last instead of $lastN.

Example 3 — Last 2 After $sort

Goal: last two products per store after sorting by highest amount first. Those trailing values are the cheaper items. $lastN does not sort—so we $sort before $group.

mongosh
db.orders.aggregate([
  // Highest amount first — trailing docs = cheaper items
  { $sort: { amount: -1 } },
  {
    $group: {
      _id: "$store",
      lastProducts: {
        $lastN: {
          input: "$product",
          n: 2
        }
      }
    }
  },
  { $sort: { _id: 1 } }
]);

How It Works

  1. Sort the pipeline. { amount: -1 } puts expensive orders ahead of cheap ones.
  2. Group still buckets by store. Within each bucket, documents keep the sorted order.
  3. Last N now means “cheapest after that sort”. Store A: Keyboard (75), then Mouse (25).
  4. Contrast Example 2. Without sort, store A was Keyboard + Monitor. With sort, Monitor is replaced by Mouse.
  5. Rank inside the accumulator? Use $bottomN with sortBy instead of a separate $sort.

Edge Cases & Pitfalls

Check these before shipping a last-N report.

order

$lastN does not sort

Without $sort, “last” only means document arrival order. Add $sort whenever business order matters.

n

Fewer than n documents is OK

The array is simply shorter. You never get padding or an error for a short group.

null

Null and missing become null

$lastN does not skip nulls. Filter with $match if you do not want them in the array.

version

Requires MongoDB 5.2+

Older servers lack $lastN. On older versions, combine $sort, $group, and $push with a later slice.

Performance Notes

ApproachCostBest for
$lastNKeeps at most n values per groupAlready-sorted pipelines
$sort + $lastNSort cost + small accumulatorTrailing-N lists with upstream sort
$bottomNRanks inside $groupWhen you prefer sortBy in the accumulator

Prefer $lastN when documents are already ordered. Keep n small and filter early with $match so fewer documents enter each group.

Key Takeaways

  • Role: array of the last N input values per group.
  • Keys: input + n (both required).
  • Order: arrival order—add $sort when it matters.
  • vs $bottomN: sorted upstream vs sortBy inside the accumulator.

One line: $lastN keeps the trailing N values per group—sort first when “last” means something specific.

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 or the trailing N events after you $sort.
Inside $group: { lastThree: { $lastN: { input: "$product", n: 3 } } }. Both input and n are required. It can also slice the last N elements from an array in $project / $addFields.
Yes whenever order matters. $lastN does not sort—it takes the last N documents as they enter each group. Add $sort before $group so “last” means latest, cheapest, or most recent.
$last returns one value from the final document. $lastN returns an array of up to N values. Use $last for a single field; use $lastN for a short trailing list.
$lastN assumes documents are already ordered (usually via $sort). $bottomN sorts inside $group with sortBy. Prefer $lastN when you sorted upstream; prefer $bottomN when ranking happens in the accumulator.
$lastN returns every available element—never more than exist. A group with two documents and n: 3 yields an array of two items.

Next: $max

Return the largest value in each group.

$max tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful