For instance I have a collection:
{ "_id" : 1, "name" : "abc", "score" : 10 }
{ "_id" : 2, "name" : "abc", "score" : 15 }
{ "_id" : 3, "name" : "abc", "score" : 20 }
{ "_id" : 4, "name" : "xyz", "score" : 10 }
{ "_id" : 5, "name" : "xyz", "score" : 15 }
{ "_id" : 6, "name" : "xyz", "score" : 20 }
How can I do a query in Mongodb to group by name
then sort by score
and take it with limit=2
. I want to get like this:
{"_id": "abc", "items": [
{ "_id" : 3, "name" : "abc", "score" : 20 },
{ "_id" : 2, "name" : "abc", "score" : 15 }]
}
{"_id": "xyz", "items": [
{ "_id" : 6, "name" : "xyz", "score" : 20 },
{ "_id" : 5, "name" : "xyz", "score" : 15 }]
}