在mongodb中分组多个文档

时间:2018-05-30 06:53:32

标签: javascript mongodb grouping

我正在尝试创建一个基于多轮的高尔夫排行榜,这意味着玩家可以使用相同的比赛进行2轮比赛。如果只有一轮,这很简单,我这样做:

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

但是,如果一场比赛有一轮以上的比赛,我对于如何对每个球员进行分组,添加轮次的分数然后对它们进行排序有点不知所措?

我走这条路,但不确定这是不是正确的方法?

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++;
    }

}

我真的希望有人可以指导我朝着正确的方向前进。

提前致谢: - )

------------编辑-----------

以下是文件的例子

{"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}

结果应为:

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

2 个答案:

答案 0 :(得分:1)

这是让你前进的方法:

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
}])

答案 1 :(得分:0)

您可以使用MongoDB聚合。

下面的示例代码
db.roundScores.aggregate({
$group: {
    _id: "$playerId", 
    toPar: { $sum: "$toPar" },
    {$sort:{"toPar":1}}
 }
})

这将有效