How to aggregate value of inner array in MongoDB? -


my document structure:

{"id"   : 1     "apps" : [         {             "name" : "app1",             "date_added" : timestamp(1453470861, 1),             "power" : [                 {                     "date" : timestamp(1453470960, 1),                     "amount" : 30.3739953125                 },                 {                     "date" : timestamp(1453470960, 1),                     "amount" : 30.3739953125                 },                 {                     "date" : timestamp(1453470960, 1),                     "amount" : 30.3739953125                 },                 {                     "date" : timestamp(1453470967, 1),                     "amount" : 30.30951765625                 }         }] } 

i have multiples apps in document posted one.

i want group apps.name , sum of power.amount each app. code came with:

db.x.aggregate([{$match:{id:1}},{$unwind:"$apps"},{$group:{_id:"$apps.name",total:{$sum:"$apps.power.amount"}}}]) 

but result:

{ "_id" : "app1", "total" : 0 } 

could tell me causes query give 0 answer?

try $unwind "power" before count it.

this proposal :

db.x.aggregate([{$match:{id:1}},{$unwind:"$apps"},{$unwind:"$apps.power"},{$group:{_id:"$apps.name",total:{$sum:"$apps.power.amount"}}}]) 

Comments