$last (aggregation)

Definition

  • $last
  • Returns the value that results from applying an expression to thelast document in a group of documents that share the same group bya field. Only meaningful when documents are in a defined order.

$last is only available in the$group stage.

$last has the following syntax:

  1. { $last: <expression> }

For more information on expressions, see Expressions.

Behavior

When using $last in a $group stage, the$group stage should follow a $sort stage tohave the input documents in a defined order.

Note

Although the $sort stage passes ordered documents asinput to the $group stage, $group is notguaranteed to maintain this sort order in its own output.

Example

Consider a sales collection with the following documents:

  1. { "_id" : 1, "item" : "abc", "date" : ISODate("2014-01-01T08:00:00Z"), "price" : 10, "quantity" : 2 }
  2. { "_id" : 2, "item" : "jkl", "date" : ISODate("2014-02-03T09:00:00Z"), "price" : 20, "quantity" : 1 }
  3. { "_id" : 3, "item" : "xyz", "date" : ISODate("2014-02-03T09:05:00Z"), "price" : 5, "quantity" : 5 }
  4. { "_id" : 4, "item" : "abc", "date" : ISODate("2014-02-15T08:00:00Z"), "price" : 10, "quantity" : 10 }
  5. { "_id" : 5, "item" : "xyz", "date" : ISODate("2014-02-15T09:05:00Z"), "price" : 5, "quantity" : 10 }
  6. { "_id" : 6, "item" : "xyz", "date" : ISODate("2014-02-15T12:05:10Z"), "price" : 5, "quantity" : 5 }
  7. { "_id" : 7, "item" : "xyz", "date" : ISODate("2014-02-15T14:12:12Z"), "price" : 5, "quantity" : 10 }

The following operation first sorts the documents by item anddate, and then in the following $group stage, groupsthe now sorted documents by the item field and uses the$last accumulator to compute the last sales date for each item:

  1. db.sales.aggregate(
  2. [
  3. { $sort: { item: 1, date: 1 } },
  4. {
  5. $group:
  6. {
  7. _id: "$item",
  8. lastSalesDate: { $last: "$date" }
  9. }
  10. }
  11. ]
  12. )

The operation returns the following results:

  1. { "_id" : "xyz", "lastSalesDate" : ISODate("2014-02-15T14:12:12Z") }
  2. { "_id" : "jkl", "lastSalesDate" : ISODate("2014-02-03T09:00:00Z") }
  3. { "_id" : "abc", "lastSalesDate" : ISODate("2014-02-15T08:00:00Z") }