I am trying this mongo aggregation I got the output but my requirement is to get the month name. I'm trying diffrent types of aggregation still not getting requirement output, Can anyone please help me.
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
} }
])
Output as of now:
/* 1 */
{
"year" : 2018,
"avgofozone" : 16.92,
"month" : 4
}
/* 2 */
{
"year" : 2017,
"avgofozone" : 602.013171402383,
"month" : 12
}
Expected output:
/* 1 */
{
"year" : 2018,
"avgofozone" : 16.92,
"month" : APRIL
}
/* 2 */
{
"year" : 2017,
"avgofozone" : 602.013171402383,
"month" : DECEMBER
}
I think it is not directly possible in mongo. But we can use $let
to map number to the string version of months. You can add the following as the final stage to map the number to string.
{
$addFields: {
month: {
$let: {
vars: {
monthsInString: [, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', ...]
},
in: {
$arrayElemAt: ['$$monthsInString', '$month']
}
}
}
}
}
You can provide month strings in whatever format required. For example, I have provided as [, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', ...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With