【问题标题】:Retrieve highest score for each game using aggregate in MongoDB使用 MongoDB 中的聚合检索每个游戏的最高分
【发布时间】:2021-06-20 11:41:31
【问题描述】:

我正在研究各种游戏的数据库,我想设计一个查询,返回每个游戏的最佳射手以及特定球员的详细信息。

文档结构如下:

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

我使用聚合创建了一个查询,该查询返回游戏名称和该游戏的最高分,如下所示

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 }

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

【问题讨论】:

    标签: mongodb aggregate pipeline


    【解决方案1】:
    [
      {
        $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"
          }
        }
      }
    ]
    

    【讨论】:

    • 此外,{ "$sort" : { "_id":1 } }可以添加到$group之后的查询中,使所有结果按游戏_id的递增顺序显示。
    猜你喜欢
    • 2022-12-11
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2014-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多