使用 MongoDB 返回具有最大值的每个组中的文档 [英] Return document in each group with max value using MongoDB
本文介绍了使用 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屋!
查看全文