gpt4 book ai didi

javascript - 使用 Mongodb 聚合如何将数字更改为月份名称

转载 作者:行者123 更新时间:2023-11-30 20:36:08 25 4
gpt4 key购买 nike

我正在尝试这个 mongo 数据库聚合,我得到了它的输出,但我的要求是月份名称仅显示名称。示例:monthname:January,monthname:February"请有人建议我

db.COLLECTION.aggregate([ 
{ $match: {
CREATE_DATE: {
$lte:new Date(),
$gte: new Date(new Date().setDate(new
Date().getDate()-200)
)
}
} },
{ $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
} }
])
output:
{
"_id" : {
"month" : 4,
"year" : 2018
},
"year" : 2018,
"avgofozone" : 16.92,
"month" : 4
}
expected output:
{
"_id" : {
"month" : April,
"year" : 2018
},
"year" : 2018,
"avgofozone" : 16.92,
"month" : april
}

最佳答案

MongoDB 中的日期数据类型不支持满足您的要求,因此最好的解决方案是创建您自己的集合(例如:“MyMonth”),该集合存储 12 个文档以将月份编号映射到月份名称:

    db.MyMonth.insert(
{
_id: 1,
"name": "JANUARY"
}
);
db.MyMonth.insert(
{
_id: 2,
"name": "FEBRUARY"
}
);
//...

然后,在您的聚合查询中使用 $lookup 管道与“MyMonth”连接以从月份编号中检索月份名称:

    $lookup:
{
from: "MyMonth",
localField: "month",
foreignField: "_id",
as: "month_data"
}
//...

关于javascript - 使用 Mongodb 聚合如何将数字更改为月份名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49816221/

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