Return document in each group with max value using MongoDB

限于喜欢 提交于 2019-12-30 11:34:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!