mongodb - Averaging Nested Values -


i looking way sum , average 'nested values' in document. i'm interested in averaging number of kids of user. lines gave me results of 0 .

db.getcollection('users').aggregate([    { $group: {     _id: "id",     mean: {         $avg: "$data.details.memberdetails.numberofkids"     }   } }]) 

i have read question here in stackoverflow, , problem data located in object that's located in array located in object how data looks like. useful. thanks.

 /* 1 */ { >     "_id" : "160b2af1fdf06daf3", >     "userid" : "943af0fa65da28a4", >     "data" : { >         "details" : [  >               { >                 "memberdetails" : { >                    >                         "numberofkids" : 3, >                         "statuse" : "married", >                  >                     }, >                     "memberdescroption" : { >                         "hight" : 1.80, >                         "wight" : 85, >                     } >                 } >               ] >              } >  > } 

you need flatten array first before grouping documents, use $unwind pipeline operator:

db.getcollection('users').aggregate([     { "$unwind": "$data.details" },     {         "$group": {             "_id": "id",             "mean": {                 "$avg": "$data.details.memberdetails.numberofkids"             }         }     } ]) 

Comments