我正在尝试查找共享max(num_sold)的所有文档。我不能仅对降序进行排序并执行limit(1),因为我会错过其他文档也具有相同max(num_sold)的情况。鉴于这个过于简化的数据集:
{"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中执行此操作感到有些困惑。
我已经找到了最大值,但是如何获得具有该最大值的所有文档呢?
db.t.aggregate(
{$group:{
_id:null,
num_sold:{$max:"$num_sold"}
}
}
);
{ "_id" : null, "num_sold" : 55 }
您可以通过分组num_sold
然后使用$sort
和$limit
管道阶段来仅获得具有最大价值的文档来做到这一点:
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
}
]
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句