I would like to get for each user in my collection the comment of the record with the highest value.
//myCol
[
{\'user\' : 1, \'value\':20, \"comment\":
You can $sort your documents by value before applying $group with $first
db.myCol.aggregate([
{
$sort: { value: -1 }
},
{
$group: {
_id: "$user",
value: { $first: "$value" },
comment: { $first: "$comment" },
date: { $first: "$date" }
}
},
{
$sort: { _id: 1 }
},
{
$project: {
user: "$_id",
_id: 0,
value: 1,
comment: 1,
date: 1
}
}
])