0
0
MongodbHow-ToBeginner · 3 min read

How to Use $last in Aggregation in MongoDB: Syntax and Examples

In MongoDB aggregation, use the $last operator to get the last value from a group of documents or sorted data. It returns the value of a specified field from the last document in the group or pipeline stage. Use it inside $group or $setWindowFields stages to capture the last element based on your sorting.
📐

Syntax

The $last operator is used inside aggregation stages like $group or $setWindowFields. It returns the value of the specified expression from the last document in the group or window.

  • $last: <expression> - Returns the value of the expression from the last document.

In $group, documents are grouped by a key, and $last returns the last value in the group based on the input order or after sorting.

json
{
  $group: {
    _id: <grouping_key>,
    lastValue: { $last: <field_or_expression> }
  }
}
💻

Example

This example groups sales by store and returns the last saleDate for each store. The documents are sorted by saleDate before grouping to ensure $last returns the latest date.

javascript
db.sales.aggregate([
  { $sort: { store: 1, saleDate: 1 } },
  { $group: {
      _id: "$store",
      lastSaleDate: { $last: "$saleDate" }
    }
  }
])
Output
[ { "_id": "StoreA", "lastSaleDate": ISODate("2023-05-10T00:00:00Z") }, { "_id": "StoreB", "lastSaleDate": ISODate("2023-05-12T00:00:00Z") } ]
⚠️

Common Pitfalls

One common mistake is using $last without sorting the documents first. Since $last returns the last document in the input order, not sorting can lead to unexpected results.

Another pitfall is confusing $last with $max. $last returns the last document's value, while $max returns the maximum value.

javascript
/* Wrong: No sorting, so lastSaleDate may be incorrect */
db.sales.aggregate([
  { $group: {
      _id: "$store",
      lastSaleDate: { $last: "$saleDate" }
    }
  }
])

/* Right: Sort by saleDate ascending before grouping */
db.sales.aggregate([
  { $sort: { store: 1, saleDate: 1 } },
  { $group: {
      _id: "$store",
      lastSaleDate: { $last: "$saleDate" }
    }
  }
])
📊

Quick Reference

OperatorDescriptionUsage Context
$lastReturns the value of the last document in a group or windowInside $group or $setWindowFields
$firstReturns the value of the first document in a group or windowInside $group or $setWindowFields
$maxReturns the maximum value in a groupInside $group
$sortSorts documents to control order for $last or $firstBefore $group stage

Key Takeaways

Use $last inside $group or $setWindowFields to get the last value from grouped documents.
Always sort documents before grouping if you want $last to return the latest or specific order value.
$last returns the last document's value in the input order, not the maximum value.
Confusing $last with $max can lead to wrong results; use $max for maximum values.
Sorting is essential to control which document $last picks in aggregation.