使用 mongodb 返回特定字段中具有 $max 值的文档

Fie*_*e82 5 mongodb aggregate max

我有一个包含一些足球比赛结果的 json 文件。我需要计算哪支球队在客场比赛中获胜最多,以及有多少场胜利。

我的查询是这样的:

db.football.aggregate(
{"$unwind": "$rounds"},
{"$unwind": "$rounds.matches"}, 

{"$project":
    {
        //"rounds.matches.team2.name":1,
        away_team: "$rounds.matches.team2.name",
        winner_away:
            { $cond: {if: {$gt:["$rounds.matches.score2","$rounds.matches.score1"] }, then:1,else :0} },
        _id:0   
    }
},
{"$group": {
    _id: {team_name:"$away_team"},
    total_wins: {$sum:"$winner_away"}
    }
}
)
Run Code Online (Sandbox Code Playgroud)

我得到的是这样的:

{ "_id" : { "team_name" : "Stoke City" }, "total_wins" : 6 }
{ "_id" : { "team_name" : "Newcastle United" }, "total_wins" : 2 }
{ "_id" : { "team_name" : "Chelsea" }, "total_wins" : 7 }
{ "_id" : { "team_name" : "Everton" }, "total_wins" : 5 }
{ "_id" : { "team_name" : "Bournemouth" }, "total_wins" : 6 }
{ "_id" : { "team_name" : "Manchester United" }, "total_wins" : 7 }
{ "_id" : { "team_name" : "Liverpool" }, "total_wins" : 8 }
{ "_id" : { "team_name" : "Manchester City" }, "total_wins" : 7 }
{ "_id" : { "team_name" : "Leicester City" }, "total_wins" : 11 }
Run Code Online (Sandbox Code Playgroud)

如果我添加这个以获得更多获胜球队的名称和获胜次数

{"$group": {
        _id: "$team_name",
        max_wins: {$max: "$total_wins"}
        }
    }   
Run Code Online (Sandbox Code Playgroud)

我明白了

{ "_id" : null, "max_wins" : 11 }
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我如何获得这个名字吗?我可以使用排序、限制来做到这一点,但如果两个或更多团队获胜次数相同,这将不起作用。

Fie*_*e82 2

我所做的是:导出到一个新集合temp,然后按 Total_winds 分组,按 ID 排序并获取第一个元素。它不仅返回第一个,而且返回所有相等的。

  db.temp.aggregate([
  {$group: {
      _id: "$total_wins",
      my_winner: {$push: "$$ROOT"}
  }},
  {$sort:{_id:-1}},
  {$limit:1}  ]).pretty()
Run Code Online (Sandbox Code Playgroud)