Search code examples
mongodbmongoosenosql-aggregation

How to match and group in multiple cases in mongodb aggregation?


i have 4 players with there scores in different matches. e.g

{user: score} -- json keys
{'a': 10}, {'a':12}, {'b':16}

I am trying to find out a way in which i can found sum of single player using aggregation function.

users.aggregation([{$match:{'user':'a'}},{$group:{_id: null, scores:{$sum:'$score'}])

i am repeating same thing for b also and continue

In shot i am doing same thing for different users for too many times.

What is the best way or different way or optimize way, so i can write aggregate query once for all users


Solution

  • You can just match out the required users with the $in clause, and then group as @Sourbh Gupta suggested.

    db.users.aggregate([
    {$match:{'user':{$in: ['a', 'b', 'c']}}},
    {$group:{_id: '$user', scores:{$sum:'$score'}}}
    ])