使用MongoDB返回每个组中具有最大价值的文档 [英] Return document in each group with max value using MongoDB

查看:63
本文介绍了使用MongoDB返回每个组中具有最大价值的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出数据集:

{_id: 0, type: 'banana', amount: 5}
{_id: 1, type: 'banana', amount: 3}
{_id: 2, type: 'apple', amount: 8}
{_id: 3, type: 'apple', amount: 2}

仅获取具有最高amount的同一type的记录的最有效方法是什么?

What is the most efficient way of getting only the records of the same type, that has the highest amount?

预期结果是:

{_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] }
     }
   }
])

推荐答案

您可以将以下聚合与 $sort 金额递减,后跟 $first 运算符以投影最大数量的文档.

You can use below aggregation with $sort amount descending followed by $first operator to project max amount document.

$replaceRoot 可以将最大数量的文档提升为顶层.

$replaceRoot to promote the max amount document to top level.

collection.aggregate([
 {$sort:{'amount':-1}}, 
 {$group:{ _id: '$type',group:{$first:'$$ROOT'}}},
 {$replaceRoot:{newRoot:"$group"}}
])

这篇关于使用MongoDB返回每个组中具有最大价值的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆