如何在mongo聚合中将数字转换为月份 [英] how to convert number to month in mongo aggregation

查看:75
本文介绍了如何在mongo聚合中将数字转换为月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试这个 mongo 聚合我得到了输出,但我的要求是得到月份名称.我正在尝试不同类型的聚合仍然没有获得需求输出,任何人都可以帮助我.

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
            } }
       ])

截至目前的输出:

/* 1 */
    {
       "year" : 2018,
       "avgofozone" : 16.92,
       "month" : 4
    }

/* 2 */
    {
       "year" : 2017,
       "avgofozone" : 602.013171402383,
       "month" : 12
    }

预期输出:

/* 1 */
    {
        "year" : 2018,
        "avgofozone" : 16.92,
        "month" : APRIL
    }

/* 2 */
   {
       "year" : 2017,
       "avgofozone" : 602.013171402383,
       "month" : DECEMBER
   }

推荐答案

我认为在 mongo 中不能直接实现.但是我们可以使用 $let 将数字映射到月份的字符串版本.您可以添加以下作为将数字映射到字符串的最后阶段.

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']
                }
            }
        }
    }
}

您可以提供任何所需格式的月份字符串.例如,我提供了 [, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', ...]

You can provide month strings in whatever format required. For example, I have provided as [, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', ...]

这篇关于如何在mongo聚合中将数字转换为月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆