Mansa
Mansa

Reputation: 2325

Grouping multiple documents in mongodb

I am trying to create a golf leaderboard based on multiple rounds, which means that a player can have played 2 rounds with the same matchid. It is pretty simple if there is just one round, I do it like this:

db.roundScores.find( { "matchId": matchId } ).sort({"data.scoreTotals.toPar": 1});

But, if a match have more than one round, I am a little in the dark on how i group each player, add the scores for the rounds and then sort them?

I am walking down this way, but not sure if this is the right way?

var allRounds = db.rounds.find( { "matchId": matchId } );

var playerScores = [];
while( allRounds.hasNext() ) {

    var thisRound = allRounds.next();
    var allScores = db.roundScores.find( { "roundId": thisRound._id.$oid } );

    var i = 0;
    while( allScores.hasNext() ) {
        var thisScore = allScores.next();

        if(i > 0){

            // Should be updating the playerScores array finding the object for the player, But how???

        } else {

            // Creating a new object and adding it to the playerScores array //
            playerScores.push({
                "id":   thisScore.playerId,
                "toPar": thisScore.scoretotals.toPar,
                "points": thisScore.scoretotals.points
            });

        }

        i++;
    }

}

I really hope that someone can guide me in the right direction on this.

Thanks in advance :-)

------------ EDIT -----------

Here is examples on the documents

{"roundId": "8745362738", "playerId": "12653426518", "toPar": 3, "points": 27}
{"roundId": "8745362738", "playerId": "54354245566", "toPar": -1, "points": 31}
{"roundId": "7635452678", "playerId": "12653426518", "toPar": 1, "points": 29}
{"roundId": "7635452678", "playerId": "54354245566", "toPar": 2, "points": 23}

The result should be:

1 playerId 54354245566 toPar 1 points 10
2 playerId 12653426518 toPar 4 points 2

Upvotes: 0

Views: 31

Answers (2)

dnickless
dnickless

Reputation: 10918

Here is something to get you going:

db.roundScores.aggregate([{
    $group: {
        _id: "$playerId", // group by playerId
        toPar: { $sum: "$toPar" }, // sum up all scores
        points: { $sum: { $max: [ 0, { $subtract: [ "$points", 25 ] } ] } }, // sum up all points above 25
    }
}, {
    $sort: { "toPar": 1 } // sort by toPar ascending
}])

Upvotes: 1

Kannan T
Kannan T

Reputation: 1759

You can go with MongoDB aggregation for this. A sample code below

db.roundScores.aggregate({
$group: {
    _id: "$playerId", 
    toPar: { $sum: "$toPar" },
    {$sort:{"toPar":1}}
 }
})

This will work

Upvotes: 0

Related Questions