gpt4 book ai didi

javascript - 如何使用芒果聚合获得另一种模式的输出

转载 作者:行者123 更新时间:2023-12-03 02:13:45 25 4
gpt4 key购买 nike

你好,我的问题是如何从数据库获取最近四个月的记录。我得到了输出,但没有得到我预期的模式,所以如何做到这一点任何人都可以帮助我解决这个问题。

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',
avgofozone:'$avgofozone',
month:'$_id.month',_id:0
}
}
])

输出是:

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

预期输出:

zone_type       year        january   febravary           march
avgofozone 2018 17.8 21.07777 17.8

最佳答案

您已经拥有所需的数据,而不是尝试从 MongoDB 中准确获取所需的数据,为什么不在应用程序层中对其进行格式化呢?

一些简单的 JavaScript 可以做到这一点:

const months = [
'January', 'February', 'March', 'April', 'May',
'June', 'July', 'August', 'September',
'October', 'November', 'December'
];

function monthNumToName(monthnum) {
return months[monthnum - 1];
}

const results = [{
"avgofozone": 21.07777777777778,
"year": 2018,
"month": 2
}, {
"avgofozone": 17.8,
"year": 2018,
"month": 3
}, {
"avgofozone": 17.8,
"year": 2018,
"month": 1
}];

const statsByYear = results.reduce((a, c) => {
const {
year,
month,
avgofozone
} = c;
if (!a[year])
a[year] = {
zone_type: 'avgofozone',
year,
[monthNumToName(month)]: avgofozone
}
else a[year][monthNumToName(month)] = avgofozone
return a;
}, {});
const formatted = Object.keys(statsByYear).map(k => {
return statsByYear[k];
});

console.log(formatted);

关于javascript - 如何使用芒果聚合获得另一种模式的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49443346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com