MongoDB的数组元素的总平均 [英] mongodb aggregate average of array elements

查看:237
本文介绍了MongoDB的数组元素的总平均的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的MongoDB中2.6.11文档集合,其中CPU是数组显示[CPU0,CPU1],见下面的例子

  {CPU:['100','20'],主机名:主机1,_ ID:1},
{CPU:['40','30'],主机名:主机1,_ ID:2}等

我在寻找的主机1',这是['70','25'(因为'100'+'40'/ 2 = '70'和'20'+'30'='平均CPU 25')。我想骨料CPU1但它没有给我正确的结果。

  db.collection.aggregate(
    [
        {
            $组:
            {
                _id:主机名
                avgCPU:{$平均:$ cpu.1}
            }
        }
    ]
);


解决方案

在MongoDB中的聚合2.6位置表示法不支持,你将需要 $放松您的文档,在下一阶段执行 $平均

在MondoDB 3.2然而,你有$ arrayElemAt运营商在其指定的索引返回元素 {$ arrayElemAt:[<阵&GT中,<&IDX GT; ]}

根据您发布的文件结构,这种查询将做的工作:

  db.cpu.aggregate([
{$放松:$ CPU},
{$组:{
   _id:$ _id
   第一:{$第一:$ CPU},
   最后:{$最后:$ CPU}
}},
{$组:{
   _id:0,
   firstAvg:{$平均:$第一},
   lastAvg:{$平均:$最后一个}
}}
]);

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"}
            }
        }
    ]
);

解决方案

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"}
}}
]);

这篇关于MongoDB的数组元素的总平均的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆