Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB group by with sort and limit for each group [duplicate]

Tags:

mongodb

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 }]
    }
like image 610
anton Avatar asked Jan 03 '23 12:01

anton


1 Answers

My solution is

db.collection.aggregate([
    {$sort:{name:-1, score:-1}},
    {$group:{_id:"$name",items:{$push:{score:"$score"}}}}, 
    {$project:{items:{$slice:["$items", 2]}}}])
.pretty()

returns

{
    "_id" : "abc",
    "items" : [
        {
            "score" : 20
        },
        {
            "score" : 15
        }
    ]
}
{
    "_id" : "xyz",
    "items" : [
        {
            "score" : 20
        },
        {
            "score" : 15
        }
    ]
}
like image 118
anton Avatar answered Jan 13 '23 22:01

anton