mongodb aggregate average of array elements

空扰寡人 提交于 2019-12-23 04:14:08

问题


I have collection of documents in mongodb 2.6.11 where 'cpu' is 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 for average cpu on 'host1' which is ['70','25'] ( because '100'+'40'/2='70' and '20'+'30'='25' ). I am trying aggregate for cpu1 but it is not giving me right result

db.collection.aggregate(
    [
        {
            $group:
            {
                _id:"hostname",
                avgCPU: {$avg: "$cpu.1"}
            }
        }
    ]
);

回答1:


In MongoDB 2.6 positional notation in aggregation is unsupported, you will need to $unwind your document, and on the next stage perform the $avg.

In MondoDB 3.2 however, you have the $arrayElemAt operator which return the element at specified index { $arrayElemAt: [ <array>, <idx> ] }

Based on the document structure you posted, this query will do the work:

db.cpu.aggregate([
{$unwind: "$cpu"},
{$group: {
   _id: "$_id",
   first: {$first: "$cpu"},
   last: {$last: "$cpu"}
}},
{$group: {
   _id: 0,
   firstAvg: {$avg: "$first"},
   lastAvg: {$avg: "$last"}
}}
]);


来源:https://stackoverflow.com/questions/35226104/mongodb-aggregate-average-of-array-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!