I have the following data in my collection "people":
{"name" : "Anton", "age" : 22, "city" : "New York"}
{"name" : "Anton", "age" : 21, "city" : "London"}
{"name" : "Anton", "age" : 20, "city" : "Berlin"}
{"name" : "Berta", "age" : 20, "city" : "Berlin"}
I want Mongo to give me the youngest people 1 per name with all its attributes (whole document) - which is:
{"name" : "Anton", "age" : 20, "city" : "Berlin"}
{"name" : "Berta", "age" : 20, "city" : "Berlin"}
With the following query:
db.people.aggregate( [
{
$group:{
_id:"$name",
"age": {$min:"$age"},
city : { $first: "$city" }
}
}
] );
Mongo will give me:
{"_id" : "Anton", "age" : 20, "city" : "New York"} // Wrong City
{"_id" : "Berta", "age" : 20, "city" : "Berlin"}
Since I am using "$first" for the city attribute, Mongo chooses the city of the first person in the group "Anton" but the city of the youngest Anton. (I am okay with the "_id" instead of "name" in the result.)
I couldn't find a solution by googling and trawling the Mongo docs for hours.
I would be glad if anybody could correct my query in order to achieve what I need.