0
0
MongoDBquery~5 mins

$first and $last accumulators in MongoDB

Choose your learning style9 modes available
Introduction

These accumulators help you pick the first or last value from a group of data. They are useful when you want to find the earliest or latest item in a list.

When you want to find the first sale date for each product.
When you want to get the last comment made on a post.
When you want to find the first or last entry in a sorted list of records.
When you want to summarize data by picking the earliest or latest value in each group.
Syntax
MongoDB
{ $group: { _id: <grouping_key>, firstValue: { $first: <expression> }, lastValue: { $last: <expression> } } }
The $first and $last accumulators return the value of the first or last document in the group, based on the order of documents entering the $group stage.
To control which document is first or last, use a $sort stage before $group.
Examples
This groups documents by category and picks the first product in each category.
MongoDB
{ $group: { _id: "$category", firstProduct: { $first: "$product" } } }
This groups documents by user and picks the last login date for each user.
MongoDB
{ $group: { _id: "$user", lastLogin: { $last: "$loginDate" } } }
Sample Program

This query sorts sales by date ascending, then groups by product. It finds the first and last sale date for each product.

MongoDB
db.sales.aggregate([
  { $sort: { date: 1 } },
  { $group: {
      _id: "$product",
      firstSaleDate: { $first: "$date" },
      lastSaleDate: { $last: "$date" }
    }
  }
])
OutputSuccess
Important Notes

Always sort your data before using $first or $last to get meaningful results.

If you do not sort, the first and last values depend on the natural order of documents, which may be unpredictable.

Summary

$first and $last pick the first or last value in a group.

Use $sort before $group to control which values are first or last.

They help summarize data by earliest or latest values.