Here is my mongo collection 'sales':
{"title":"Foo", "hash": 17, "num_sold": 49,
"place": "ABC"}
{"title":"Bar", "hash": 18, "num_sold": 55,
"place": "CDF"}
{"title":"Baz", "hash": 17, "num_sold": 55,
"place": "JKN"}
{"title":"Spam", "hash": 17, "num_sold": 20,
"place": "ZSD"}
{"title":"Eggs", "hash": 18, "num_sold": 20,
"place": "ZDF"}
I would like to group by hash and return document with the greatest "num_sold". So as output I would like to see:
{"title":"Baz", "hash": 17, "num_sold": 55,
"place": "JKN"}
{"title":"Bar", "hash": 18, "num_sold": 55,
"place": "CDF"}
I know basic of aggregate operator and here is how I would group and get maximum of num_sold, but I need whole document corresponding to maximum, not just the value.
db.getCollection('sales').aggregate([
{$group: {_id: "$hash", max_sold : {$max: '$value'}}}
])
In SQL I would have done it with join, but in mongo. I also read that in mongo group and sort do not work well together.