I have several documents that look like this:
{ "_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 },] }
I am trying to combine this data. First, expand the array, and then leave only “ football ” and “ cycling ”, then the result is average . This part I did, and it works. My code is:
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"}}}, )
Then I try to aggregate by league_id , which means that average players lead to certain leagues, add to the code above: {$group:{_id:"$_id.league_id",aver_league:{$avg:$average}}}
And now the code is as follows:
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}}} )
Console Displays: JavaScript execution failed: ReferenceError: $average is not defined. What's wrong? Where did I make a mistake? Is it possible to aggregate the value of _id.league_id ?