Nati Barchilon
Nati Barchilon

Reputation: 43

Averaging Nested Values

i was looking for a way to sum and to average 'nested values' in that document. I'm interested in averaging the number of kids of a user. Those lines gave me a results of 0 .

db.getCollection('users').aggregate([
   {
$group: {
    _id: "id",
    Mean: {
        $avg: "$data.details.MemberDetails.numberOfKids"
    }
  }
}])

I have read some question here in stackoverflow, and the problem that my data is located in an object that's located in an array which is located in an object This is how the data looks like. Any help will be useful. Thanks.

 /* 1 */
{
>     "_id" : "160b2af1fdf06daf3",
>     "userId" : "943af0fa65da28a4",
>     "data" : {
>         "details" : [ 
>               {
>                 "MemberDetails" : {
>                   
>                         "numberOfKids" : 3,
>                         "Statuse" : "married",
>                 
>                     },
>                     "MemberDescroption" : {
>                         "hight" : 1.80,
>                         "wight" : 85,
>                     }
>                 }
>               ]
>              }
> 
> }

Upvotes: 0

Views: 43

Answers (1)

chridam
chridam

Reputation: 103435

You need to flatten the array first before grouping the documents, use the $unwind pipeline operator:

db.getCollection('users').aggregate([
    { "$unwind": "$data.details" },
    {
        "$group": {
            "_id": "id",
            "Mean": {
                "$avg": "$data.details.MemberDetails.numberOfKids"
            }
        }
    }
])

Upvotes: 2

Related Questions