Du kan använda $last och $first operatörer. Observera att du bör sortera dokument innan du grupperar:
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 } }
])
Utdata:
{
"_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
}