如何使用MongoDB计算每日平均字段? [英] How to calculate average per day field using MongoDB?

查看:283
本文介绍了如何使用MongoDB计算每日平均字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须计算每天收集的平均费用.我每分钟创建一个查询.现在,我想将此查询转换为每天的平均值. 我的每分钟查询情况如下

I have to calculate per day average of collection filed. I created one query on per minute basis. Now I want to convert this query in per day average. My per minute query as follows

 db.voltage.aggregate(
{
  $unwind: {
        path:"$KeyValues",
        includeArrayIndex:"arrayIndex",
        preserveNullAndEmptyArrays:true
    }
},
{
  $project: {
          timestamp:{
"$add":["$EventTS",{"$multiply":[60000,"$arrayIndex"]}]
          } ,
        "RVoltage":"$KeyValues.RVoltage",
        arrayIndex:1,
        }
},
{
  $match: {
      $and: [
          {RVoltage: {$ne: null}}
       ]
  }
}
);

您能建议我如何计算每天的平均值吗?

Can you suggest me how to calculate average per day?

推荐答案

按日期分组

db.voltage.aggregate([
    {$project: {
        date: {$dateToString: {format: "%Y-%m-%d", date: "$EventTS"}},
        KeyValues:1
    }},
    {$unwind: '$KeyValues'},
    {$project: {
       date: 1,
       RVoltage: '$KeyValues.RVoltage'
    }},
    {$group: {
        _id: '$date',
        avg: {$avg: '$RVoltage'}
    }},
    {$sort: {_id: 1}}
])
{ "_id" : "2015-07-02", "avg" : 234.1845454545454 }
{ "_id" : "2016-06-30", "avg" : 249.9316666666667 }
{ "_id" : "2016-07-01", "avg" : 244.08681818181822 }

这篇关于如何使用MongoDB计算每日平均字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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