VAR*_*RUN 1 aggregation mongoose mongodb mongodb-query
我正在尝试此mongo聚合,但得到了输出,但我的要求是获取月份名称。我正在尝试不同的聚合类型,但仍未获得需求输出,任何人都可以帮助我。
db.collection.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
} }
])
Run Code Online (Sandbox Code Playgroud)
截至目前的输出:
/* 1 */
{
"year" : 2018,
"avgofozone" : 16.92,
"month" : 4
}
/* 2 */
{
"year" : 2017,
"avgofozone" : 602.013171402383,
"month" : 12
}
Run Code Online (Sandbox Code Playgroud)
预期产量:
/* 1 */
{
"year" : 2018,
"avgofozone" : 16.92,
"month" : APRIL
}
/* 2 */
{
"year" : 2017,
"avgofozone" : 602.013171402383,
"month" : DECEMBER
}
Run Code Online (Sandbox Code Playgroud)
我认为在mongo中不是直接可能的。但是我们可以使用$let将数字映射到月份的字符串版本。您可以添加以下内容作为将数字映射到字符串的最后阶段。
{
$addFields: {
month: {
$let: {
vars: {
monthsInString: [, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', ...]
},
in: {
$arrayElemAt: ['$$monthsInString', '$month']
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以按要求的任何格式提供月份字符串。例如,我提供了[, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', ...]
| 归档时间: |
|
| 查看次数: |
1185 次 |
| 最近记录: |