I want to get "all documents" that have the highest value for a particular field and then grouped by another field.
Consider the data below:
_id:1, country:india, quantity:12, name:xyz
_id:2, country:USA, quantity:5, name:abc
_id:3, country:USA, quantity:6, name:xyz
_id:4, country:india, quantity:8, name:def
_id:5, country:USA, quantity:10, name:jkl
_id:6, country:india, quantity:12, name:jkl
The answer should be
country:india max-quantity:12
name xyz
name jkl
country:USA max-quantity:10
name jkl
I tried several queries, but I can only get the maximum value without a name, or I can group, but it shows all the values.
db.coll.aggregate([{
$group:{
_id:"$country",
"maxQuantity":{$max:"$quantity"}
}
}])
for example, the above will give the maximum quantity for each country, but how to combine with another field so that it displays all documents of the maximum quantity.
user4549111
source
share