使用 MongoDB 中的聚合检索每场比赛的最高分

Retrieve highest score for each game using aggregate in MongoDB

我正在处理各种游戏的数据库,我想设计一个查询 returns 每个游戏的最佳射手以及特定玩家的详细信息。

文档结构如下:

db.gaming_system.insertMany(
    [
        {
            "_id": "01",
            "name": "GTA 5",
            "high_scores": [
                {
                    "hs_id": 1,
                    "name": "Harry",
                    "score": 6969
                },
                {
                    "hs_id": 2,
                    "name": "Simon",
                    "score": 8574
                },
                {
                    "hs_id": 3,
                    "name": "Ethan",
                    "score": 4261
                }
            ]
        },
        {
            "_id": "02",
            "name": "Among Us",
            "high_scores": [
                {
                    "hs_id": 1,
                    "name": "Harry",
                    "score": 926
                },
                {
                    "hs_id": 2,
                    "name": "Simon",
                    "score": 741
                },
                {
                    "hs_id": 3,
                    "name": "Ethan",
                    "score": 841
                }
            ]
        }
    ]
)

我使用聚合创建了一个查询,其中returns游戏名称和该游戏的最高分如下

db.gaming_system.aggregate(
    { "$project": { "maximumscore": { "$max": "$high_scores.score" }, name:1 } }, 
    { "$group": { "_id": "$_id", Name: { $first: "$name" }, "Highest_Score": { "$max": "$maximumscore" } } },
    { "$sort" : { "_id":1 } }
)

我的查询输出如下:

{ "_id" : "01", "Name" : "GTA 5", "Highest_Score" : 8574 }
{ "_id" : "02", "Name" : "Among Us", "Highest_Score" : 926 }

我想生成输出,其中还提供玩家的姓名和每场比赛得分最高的玩家的“hs_id”,如下所示:

{ "_id" : "01", "Name" : "GTA 5", "Top_Scorer" : "Simon", "hs_id": 2, "Highest_Score" : 8574 }
{ "_id" : "02", "Name" : "Among Us", "Top_Scorer" : "Harry", "hs_id": 1, "Highest_Score" : 926 }

应该使用聚合管道将什么添加到我的查询中?

[
  {
    $unwind: "$high_scores" //unwind the high_scores, so you can then sort
  },
  {
    $sort: {
      "high_scores.score": -1 //sort the high_scores, irrelevant of game, because we are going to group in next stage
    }
  },
  {
//now group them by _id, take the name and top scorer from $first (which is the first in that group as sorted by score in descending order

    $group: {
      _id: "$_id",
      name: {
        $first: "$name"
      },
      Top_Scorer: {
        $first: "$high_scores"
      }
    }
  }
]