我正在尝试这个mongo数据库聚合我得到了它的输出,但我的要求是月份名称只显示名称.example:monthname:January,monthname:February“plase任何人建议我
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
}
答案 0 :(得分:0)
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"
}
//...