Dagron
Dagron

Reputation: 185

how can I find the average of the sums of a field?

I have documents that looks like this

{ parentId: 2,  childId: 4, data: 7 },
{ parentId: 2,  childId: 3, data: 5 },
{ parentId: 2,  childId: 3, data: 1 }

I would like to pull the average of the sum of the data grouped by the childId where the parentId = a specific ID.

for example the data I would like to return by a given parent ID (2) is

((5 + 1) + (7)) / 2

Is there are way to nest the $sum inside a $avg or do I just need to return a list of the sums grouped by the childId and then average them myself?

Upvotes: 0

Views: 61

Answers (1)

Sede
Sede

Reputation: 61273

First $sum data group by childId then find $avg of the sums.

db.collection.aggregate(
    [
        { "$match": { "parentId": 2 }}, 
        { "$group": { "_id": "$childId", "sumdata": { "$sum": "$data" }}},
        { "$group": { "_id": "null", "avgdata": { "$avg": "$sumdata" }}}, 
    ]
)
{ "avgdata" : 6.5 }

Upvotes: 2

Related Questions