U kunt $last gebruiken en $first exploitanten. Merk op dat u documenten moet sorteren voordat u ze groepeert:
db.so.aggregate([
{ $sort: {productID:-1, date: -1} },
{
$group: {
_id : "$productID",
date: {$last: "$date" },
amount: {$first: "$amount" },
id : {$first: "$_id"}
}
},
{ $project: { _id: "$id", productId: "$_id", date: 1, amount: 1 } }
])
Uitgang:
{
"_id" : 5,
"productId" : 1,
"date" : ISODate("2017-02-01T00:00:00.000Z"),
"amount" : 11
},
{
"_id" : 7,
"productId" : 2,
"date" : ISODate("2017-02-01T00:00:00.000Z"),
"amount" : 222
},
{
"_id" : 8,
"productId" : 3,
"date" : ISODate("2017-02-01T00:00:00.000Z"),
"amount" : 33
},
{
"_id" : 4,
"productId" : 4,
"date" : ISODate("2017-02-01T00:00:00.000Z"),
"amount" : 4
}