我有几个看起来像这样的文件:
{
"_id" : ObjectId("50b59cd75bed76f46522c34e"),
"player_id" : 0,
"league_id" : 2,
"results" : [
{ "discipline" : "football",
"score" : 25.15
},
{
"discipline" : "basketball",
"score" : 21.24
},
{
"discipline" : "cycling",
"score" : 68.19
},]
}
我尝试汇总这些数据。首先展开结果数组,然后只留下“足球”和“自行车”,然后计算平均结果。这部分我做了,它正在工作。我的代码:
db.grades.aggregate(
{$unwind:"$results"},
{$match: {$or: [{"results.discipline":"football"},{"results.discipline":"cycling"} ]}},
{$group:{_id:{player_id:"$player_id",league_id:"$league_id"}, 'average':{$avg:"$results.score"}}},
)
然后我尝试通过League_id进行聚合,这意味着平均球员在特定联赛中的成绩,添加到上面的代码中:
{$group:{_id:"$_id.league_id",aver_league:{$avg:$average}}}
现在代码看起来像:
db.grades.aggregate(
{$unwind:"$results"},
{$match: {$or: [{"results.discipline":"football"},{"results.discipline":"cycling"} ]}},
{$group:{_id:{player_id:"$player_id",league_id:"$league_id"}, 'average':{$avg:"$results.score"}}},
{$group:{_id:"$_id.league_id",aver_league:{$avg:$average}}}
)
控制台显示:出JavaScript execution failed: ReferenceError: $average is not defined.
了什么问题?我在哪里做错了?是否可以聚合_id.league_id
?