问题
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}
I want to get back
{"item":"Orange", "num_sold": 55}
{"item":"Peach", "num_sold": 55}
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 }
回答1:
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}
])
Output:
{
"_id" : 55.0,
"docs" : [
{
"_id" : ObjectId("5726a62879ce3350ff8d607e"),
"item" : "Orange",
"num_sold" : 55.0
},
{
"_id" : ObjectId("5726a62879ce3350ff8d607f"),
"item" : "Peach",
"num_sold" : 55.0
}
]
}
来源:https://stackoverflow.com/questions/36973145/find-all-documents-that-share-maxvalue-found-in-aggregate-step