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

5.8k views Asked by At

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

3

There are 3 answers

0
hyades On BEST ANSWER

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'}}}
])
1
Sourbh Gupta On

group the data on the basis of user. i.e.

 users.aggregation([{$group:{_id: "$user", scores:{$sum:'$score'}}}])
0
Kevin Smith On

Not too sure about your document structures, but if you've got 2 diffrent fields for 2 diffrent scores you can group together and sum then and then project and sum then 2 grouped sums (if that makes sense)

So for example, I have these docuemnts:

> db.scores.find()
{ "_id" : ObjectId("5858ed67b11b12dce194eec8"), "user" : "bob", "score" : { "a" : 10 } }
{ "_id" : ObjectId("5858ed6ab11b12dce194eec9"), "user" : "bob", "score" : { "a" : 12 } }
{ "_id" : ObjectId("5858ed6eb11b12dce194eeca"), "user" : "bob", "score" : { "b" : 16 } }

Notice we have a user bob and he has 2x a scores and 1x b score.

We can now write an aggregation query to do a match for bob then sum the scores.

db.scores.aggregate([
    { $match: { user : "bob" } },
    { $group: { _id : "$user", sumA : { $sum : "$score.a" }, sumB : { $sum : "$score.b" } } },
    { $project: { user: 1, score : { $sum: [ "$sumA", "$sumB" ] } } }
]);

This will give us the following result

{ "_id" : "bob", "score" : 38 }