[英]Grouping multiple documents in mongodb
我正在嘗試基於多個回合創建高爾夫排行榜,這意味着一個玩家可以使用相同的Matchid進行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
這是一些讓您前進的方法:
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
}])
您可以為此使用MongoDB聚合。 下面的示例代碼
db.roundScores.aggregate({
$group: {
_id: "$playerId",
toPar: { $sum: "$toPar" },
{$sort:{"toPar":1}}
}
})
這會工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.