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 even do with two stages only
db.collection.aggregate([
{ "$group": {
"_id": "$user",
"doc": {
"$max": {
"value": "$value",
"user": "$user",
"comment": "$comment",
"date": "$date"
}
}
}},
{ "$replaceRoot": { "newRoot": "$doc" }}
])
$max always takes the maximum value of the first expression which is passed inside the object. Here it is value
.
It does, but the approach is slightly different:
db.myCol.aggregate([
{$sort: {value:-1}},
{$group:{
_id: "$user",
doc: {$first: "$$ROOT"}
}},
{$replaceRoot: {newRoot: "$doc"} }
])
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
}
}
])