Return document in each group with max value using MongoDB

前端 未结 1 1981
一向
一向 2021-01-16 06:27

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\', a         


        
相关标签:
1条回答
  • 2021-01-16 07:23

    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"}}
    ])
    
    0 讨论(0)
提交回复
热议问题