Combining Two-Group MongoDB Groups

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 ?

+4
source share
1 answer

Try this pipeline:

 [ {$unwind:"$results"}, {$match: {"results.discipline":{$in:["football", "basketball"]}}}, {$group{_id:{player_id:"$player_id",league_id:"$league_id"}, 'average':{$avg:"$results.score"}}} ] 

it works for me with your document:

 { "result" : [ { "_id" : { "player_id" : 0, "league_id" : 2 }, "average" : 23.195 } ], "ok" : 1 } 

UPD If you want to group again, league_id :

 [{$unwind:"$results"}, {$match: {"results.discipline":{$in:["football", "basketball"]}}}, {$group:{_id:{player_id:"$player_id",league_id:"$league_id"}, 'average':{$avg:"$results.score"} }}, {$group:{_id:"$_id.league_id", 'average':{$avg:"$average"} }} ] { "result" : [ { "_id" : 2, "average" : 23.195 } ], "ok" : 1 } 
+4
source

Source: https://habr.com/ru/post/1486600/


All Articles