查找共享在汇总步骤中找到的最大值(值)的所有文档 [英] Find all documents that share max(value) found in aggregate step
问题描述
我正在尝试查找共享 max(num_sold)的所有文档.我不能仅对降序进行排序并执行limit(1),因为我会错过其他文档也具有相同max(num_sold)的情况.鉴于这个过于简化的数据集:
I'm trying to find all documents that share the max(num_sold). I cant just sort descending and do a limit(1) because I'd miss the case where other docs also have the same max(num_sold). Given this over-simplified dataset:
{"item":"Apple", "num_sold": 49}
{"item":"Orange", "num_sold": 55}
{"item":"Peach", "num_sold": 55}
{"item":"Grape", "num_sold": 20}
{"item":"Banana", "num_sold": 20}
我想回来
{"item":"Orange", "num_sold": 55}
{"item":"Peach", "num_sold": 55}
使用SQL,这是一个简单的查询,然后联接回主数据集.我对如何在MongoDB中执行此操作感到有些困惑.
Using SQL, this is a simple query and then join back to the main dataset. I'm a bit stumped on how to do this in MongoDB.
我已经找到了最大值,但是如何获得具有该最大值的所有文档呢?
I've found the max, but how do I get all docs that have that max?
db.t.aggregate(
{$group:{
_id:null,
num_sold:{$max:"$num_sold"}
}
}
);
{ "_id" : null, "num_sold" : 55 }
推荐答案
您可以通过在num_sold
上进行分组,然后使用$sort
和$limit
管道阶段来仅获取具有最大值的文档来做到这一点:
You can do this by grouping on num_sold
and then using $sort
and $limit
pipeline stages to get just the docs with the maximum value:
db.t.aggregate([
// Group by num_sold, assembling an array of docs with each distinct value.
{$group: {
_id: '$num_sold',
docs: {$push: '$$ROOT'}
}},
// Sort the groups by _id descending to put the max num_sold group first.
{$sort: {_id: -1}},
// Return just the first (max num_sold) group of docs.
{$limit: 1}
])
输出:
{
"_id" : 55.0,
"docs" : [
{
"_id" : ObjectId("5726a62879ce3350ff8d607e"),
"item" : "Orange",
"num_sold" : 55.0
},
{
"_id" : ObjectId("5726a62879ce3350ff8d607f"),
"item" : "Peach",
"num_sold" : 55.0
}
]
}
这篇关于查找共享在汇总步骤中找到的最大值(值)的所有文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!