Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return document in each group with max value using MongoDB

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] }
     }
   }
])
like image 953
danielsvane Avatar asked Feb 17 '26 10:02

danielsvane


1 Answers

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"}}
])
like image 56
s7vr Avatar answered Feb 21 '26 09:02

s7vr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!