如何获得最近 4 个月的平均值
how get the last 4 months average value
我正在尝试这个聚合最近 4 个月记录每个月的 OZONE 平均值但平均值为空如何获得平均值
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 }
它不起作用,因为 OZONE
字段是一个字符串,并且您无法计算字符串的 $avg
。另外,它不是一个有效的数字:"8:84"
应该是 8.84
$avg
Returns the average value of the numeric values that result from
applying a specified expression to each document in a group of
documents that share the same group by key. $avg ignores non-numeric
values.
否则聚合查询是正确的,下面是 link 显示:mongo playground.net/p/VaL-Nn8e21E
我正在尝试这个聚合最近 4 个月记录每个月的 OZONE 平均值但平均值为空如何获得平均值
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 }
它不起作用,因为 OZONE
字段是一个字符串,并且您无法计算字符串的 $avg
。另外,它不是一个有效的数字:"8:84"
应该是 8.84
$avg
Returns the average value of the numeric values that result from applying a specified expression to each document in a group of documents that share the same group by key. $avg ignores non-numeric values.
否则聚合查询是正确的,下面是 link 显示:mongo playground.net/p/VaL-Nn8e21E