【问题标题】:how get the last 4 months average value如何获得最近 4 个月的平均值
【发布时间】:2018-09-01 11:59:30
【问题描述】:

我正在尝试此聚合最近 4 个月记录每个月的臭氧平均值但平均值为空如何获得平均值

db.Air_pollution.aggregate([
 {$match:{CREATE_DATE:{$lte:new Date(),$gte:new Date(new Date().setDate(new 
   Date().getDate()-120))}}},
 {$group:{_id:{month:{$month:"$CREATE_DATE"},year:
 {$year:"$CREATE_DATE"}},avgofozone:{$avg:"$OZONE"}}},
 {$sort:{"year":-1}},{$project:
 {year:'$_id.year',month:'$_id.month',_id:0,avgofozone:1}}

])

输出:

 { "avgofozone" : null, "year" : 2018, "month" : 2 }
        { "avgofozone" : null, "year" : 2018, "month" : 3 }
        { "avgofozone" : null, "year" : 2018, "month" : 1 }

【问题讨论】:

  • 请发布样本数据集
  • @Rahul Raj "_id" : ObjectId("5ab3f0975c4f698c8a39ea22"), "DISTRICT" : "vskp", "STATION" : "appcb​​", "TAKEN_DATE" : ISODate("2018-02-25T00 :18:00.000Z")、“臭氧”:“8:84”、“pm10”:“69.0”、“pm2dots”:“49.0”、“DATA_FROM”:“vsk”、“CREATE_DATE”:ISODate(“2018 -02-05T00:30:05.867Z")

标签: mongodb mongoose mongodb-query aggregate-functions mongoose-schema


【解决方案1】:

它不起作用,因为 OZONE 字段是一个字符串,并且您无法在字符串上计算 $avg。另外,这不是一个有效的数字:"8:84" 应该是 8.84

来自mongodb documentation

$avg

返回产生的数值的平均值 将指定的表达式应用于一组中的每个文档 键共享同一组的文档。 $avg 忽略非数字 价值观。

否则聚合查询是正确的,这里有一个链接显示它:mongo playground.net/p/VaL-Nn8e21E

【讨论】:

  • @felix 好的,我明白了,谢谢,我的输出是:{ "avgofozone" : 21.07777777777778, "year" : 2018, "month" : 2 } { "avgofozone" : 17.8, "year" : 2018,“月”:3 } {“avgofozone”:17.8,“年”:2018,“月”:1 } 我预计输出:zone_type 年 1 月 2 月 3 月 avgofozone 2018 17.8 21.07777 17.8
  • 预期输出:zone_type 年 1 月 2 月 3 月 avgofozone 2018 17.8 21.07777 17.8
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
相关资源
最近更新 更多