Skip to content

Instantly share code, notes, and snippets.

@Haleluak
Created October 30, 2019 10:09
Show Gist options
  • Select an option

  • Save Haleluak/dbb101460deb3424cd355cb36e64980f to your computer and use it in GitHub Desktop.

Select an option

Save Haleluak/dbb101460deb3424cd355cb36e64980f to your computer and use it in GitHub Desktop.
Get the Most Recent Item in a Group
{ "_id": 1, "color": "red", "date": ISODate("2013-05-10T00:00:00Z") }
{ "_id": 2, "color": "blue", "date": ISODate("2016-10-20T00:00:00Z") }
{ "_id": 3, "color": "green", "date": ISODate("2015-09-14T00:00:00Z") }
{ "_id": 4, "color": "green", "date": ISODate("2015-07-19T00:00:00Z") }
{ "_id": 5, "color": "red", "date": ISODate("2017-01-04T00:00:00Z") }
{ "_id": 6, "color": "blue", "date": ISODate("2014-03-06T00:00:00Z") }
result = db.books.aggregate([
{ $sort: { "date": -1 } },
{ $group: {
_id: "$color",
books: { $push: "$$ROOT" }
}},
{ $replaceRoot: {
newRoot: { $arrayElemAt: ["$books", 0] }
}}
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment