aggregation framework - mongodb aggregate average of array elements -
i have collection of documents in mongodb 2.6.11 'cpu' array showing [cpu0,cpu1], see example below
{ cpu: [ '100','20' ], hostname: 'host1',_id: 1 }, { cpu: [ '40','30' ], hostname: 'host1',_id: 2 }, etc
i'm looking average cpu on 'host1' ['70','25'] ( because '100'+'40'/2='70' , '20'+'30'='25' ). trying aggregate cpu1 not giving me right result
db.collection.aggregate( [ { $group: { _id:"hostname", avgcpu: {$avg: "$cpu.1"} } } ] );
in mongodb 2.6 positional notation in aggregation unsupported, need $unwind
document, , on next stage perform $avg
.
in mondodb 3.2 however, have $arrayelemat operator return element @ specified index { $arrayelemat: [ <array>, <idx> ] }
based on document structure posted, query work:
db.cpu.aggregate([ {$unwind: "$cpu"}, {$group: { _id: "$_id", first: {$first: "$cpu"}, last: {$last: "$cpu"} }}, {$group: { _id: 0, firstavg: {$avg: "$first"}, lastavg: {$avg: "$last"} }} ]);
Comments
Post a Comment