Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert number to month in mongo aggregation

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
   }
like image 628
VARUN Avatar asked Dec 13 '22 17:12

VARUN


1 Answers

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', ...]

like image 132
RaR Avatar answered Jan 09 '23 18:01

RaR