go - Golang MongoDB (mgo) aggregation with nested arrays -
go - Golang MongoDB (mgo) aggregation with nested arrays -
i have mongodb info of next form:
{"_id":"53eb9a5673a57578a10074ec","data":{"statistics":{"gsm":[{"type":"attacks","value":{"team1":66,"team2":67}},{"type":"corners","value":{"team1":8,"team2":5}},{"type":"dangerous attacks","value":{"team1":46,"team2":49}},{"type":"fouls","value":{"team1":9,"team2":14}},{"type":"free kicks","value":{"team1":18,"team2":10}},{"type":"goals","value":{"team1":2,"team2":1}},{"type":"goal kicks","value":{"team1":10,"team2":11}},{"type":"offsides","value":{"team1":1,"team2":4}},{"type":"posession","value":{"team1":55,"team2":45}},{"type":"shots blocked","value":{"team1":4,"team2":1}},{"type":"shots off target","value":{"team1":7,"team2":5}}]}}} i want average of data.statistics.gsm.value.team1 when data.statistics.gsm.type == "attacks" using golang mongodb driver mgo. code have tried far (with either 1 or both grouping statements below):
pipeline := []bson.m{ bson.m{"$match": bson.m{"kick_off.utc.gsm.date_time": bson.m{"$gt": start, "$lt": end}}}, bson.m{ "$group": bson.m{ "_id": "$gsm_id", "event_array" : bson.m{"$first": "$data.statistics.gsm"}}}, bson.m{ "$group": bson.m{ "_id": "$type", "avg_attack" : bson.m{"$avg": "$data.statistics.gsm.value.team1"}}}} with first grouping statement, below, sec grouping statement doesn't help me average.
[{"_id":1953009,"event_array":[{"type":"attacks","value":{"team1":48,"team2":12}},{"type":"corners","value":{"team1":12,"team2":0}},{"type":"dangerous attacks","value":{"team1":46,"team2":7}},{"type":"fouls","value":{"team1":10,"team2":3}},{"type":"free kicks","value":{"team1":5,"team2":12}},{"type":"goals","value":{"team1":8,"team2":0}}
i find helpful pretty print view of json. here first grouping statement:
[ { "_id":1953009, "event_array":[ { "type":"attacks", "value":{ "team1":48, "team2":12 } }, { "type":"corners", "value":{ "team1":12, "team2":0 } }, ... now sec grouping statement use:
"$group": bson.m{ "_id": "$type", "avg_attack" : bson.m{"$avg": "$data.statistics.gsm.value.team1"} } you're trying take average of data.statistics.gsm.value.team1 on results of first grouping statement, doesn't exist in results of first grouping statement of course of study won't give average.
instead of approach you're using, i'd suggest looking $unwind operator break downwards array set of documents, should able grouping them in way you're trying here {$avg: "$value.team1"}.
so overall pipeline used produce aggregation be: $match -> $group1 -> $unwind -> $group2. maintain in mind each phase of pipeline operating on info produced previous stage, why data.statistics.gsm.value.team1 part incorrect.
mongodb go aggregation-framework mgo
Comments
Post a Comment