Mongodb aggregation taking average -


in mongodb, have collection has following data:

[{     _id: objectid('....'),     data: [{         type: 'internal',         name: 'abc',         value: 60     }, {         type: 'internal',         name: 'def',         value: 20     }, {         type: 'external',         name: 'def',         value: 20     }] }, {     _id: objectid('....'),     data: [{         type: 'internal',         name: 'abc',         value: 30     }, {         type: 'internal',         name: 'def',         value: 40     }, {         type: 'external',         name: 'def',         value: 10     }] }] 

now if want group type , take average of value field, can like

db.testcollection.aggregate([     {$unwind: '$data'},      {$group: {_id: '$data.type', avg: {$avg: '$data.value'}}} ]); 

but, if values of 1 document of same type has treated has 1 value(sum of both) , average has calculated, query ?

in example type internal should be:

((60+20)+(30+40))/2 

rather than

(60+20+30+40)/4 

you can in 2 $group phases. first 1 used compute sum within document , second 1 used compute average across documents.

db.testcollection.aggregate([     {$unwind: "$data"},      {$group: {_id: {_id:"$_id", type:"$data.type"}, sum:{"$sum": "$data.value"}}}     {$group:{_id:"$_id.type", avg:{"$avg":"$sum"}}} ]); 

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

How to get multiresult with multicondition in Sql Server -