mongodb - how can I find the average of the sums of a field? -
i have documents looks this
{ parentid: 2, childid: 4, data: 7 }, { parentid: 2, childid: 3, data: 5 }, { parentid: 2, childid: 3, data: 1 } i pull average of sum of data grouped childid parentid = specific id.
for example data return given parent id (2) is
((5 + 1) + (7)) / 2 is there way nest $sum inside $avg or need return list of sums grouped childid , average them myself?
first $sum data group childid find $avg of sums.
db.collection.aggregate( [ { "$match": { "parentid": 2 }}, { "$group": { "_id": "$childid", "sumdata": { "$sum": "$data" }}}, { "$group": { "_id": "null", "avgdata": { "$avg": "$sumdata" }}}, ] ) { "avgdata" : 6.5 }
Comments
Post a Comment