问题
Given a dataset:
{_id: 0, type: 'banana', amount: 5}
{_id: 1, type: 'banana', amount: 3}
{_id: 2, type: 'apple', amount: 8}
{_id: 3, type: 'apple', amount: 2}
What is the most efficient way of getting only the records of the same type
, that has the highest amount
?
The expected result is:
{_id: 0, type: 'banana', amount: 5}
{_id: 2, type: 'apple', amount: 8}
Right now I'm doing it this way, but it seems kinda silly:
collection.aggregate([
{ $sort: { 'amount': -1 } },
{ $group: {
_id: '$type',
group: {
$push: '$$ROOT'
}
}, {
$replaceRoot: {
newRoot: { $arrayElemAt: ["$group", 0] }
}
}
])
回答1:
You can use below aggregation with $sort amount descending followed by $first operator to project max amount document.
$replaceRoot to promote the max amount document to top level.
collection.aggregate([
{$sort:{'amount':-1}},
{$group:{ _id: '$type',group:{$first:'$$ROOT'}}},
{$replaceRoot:{newRoot:"$group"}}
])
来源:https://stackoverflow.com/questions/48420948/return-document-in-each-group-with-max-value-using-mongodb