我有一个包含一些足球比赛结果的 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" : …
Run Code Online (Sandbox Code Playgroud)