是否可以在MongoDB上的聚合管道内键入强制转换数据? [英] Is it possible to type cast data inside an aggregation pipeline on MongoDB?

查看:168
本文介绍了是否可以在MongoDB上的聚合管道内键入强制转换数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我需要使用MongoDB上的aggregate命令按日期汇总事物时,通常会这样做:

When I need to aggregate things by date using the aggregate command on MongoDB, I usually do this:

 db.mycollection.aggregate(
 {
        $project: {
            day: {$dayOfMonth: "$date"},
            mon: {$month: "$date"},
            year: {$year: "$date"},
        }
    },
    {
        $group: {
            _id : {day: "$day", mon: "$mon", year: "$year"},
            count: {$sum: 1}
        }
    }
 )

,并最终将daymonyear字段连接到应用程序中的日期字符串.但是由于种种原因,有时我想在离开数据库之前将这些字段连接起来,所以我最初尝试了:

and eventually concatenate the day, mon, and year fields into a date string in the application. For many reasons though, sometimes I want to concatenate the fields before leaving the database, so I initially tried:

 db.mycollection.aggregate(
 {
        $project: {
            day: {$dayOfMonth: "$date"},
            mon: {$month: "$date"},
            year: {$year: "$date"},
        }
    },
    $project: {
            datestr: {
                $concat : ["$year", "-", "$month", "-", "$day"]
            }
        }
    },

    {
        $group: {
            _id : {day: "$day", mon: "$mon", year: "$year"},
            count: {$sum: 1}
        }
    }
 )

这将不起作用,因为$concat需要字符串,并且daymonyear是整数.所以,我的问题是:我可以使用$project操作键入强制转换字段吗?

This won't work because $concat expects strings and day, mon and year are integers. So, my question is: can I type cast a field with the $project operation?

推荐答案

,您可以使用$substr将数字强制转换为字符串.您缺少的链接看起来像:

Yes, you can use $substr for casting a number to a string. Your missing link would look like:

{
    $project: {
        day_s:  { $substr: [ "$day",   0, 2 ] }, 
        mon_s:  { $substr: [ "$month", 0, 2 ] }, 
        year_s: { $substr: [ "$year",  0, 4 ] }
    }
}

这篇关于是否可以在MongoDB上的聚合管道内键入强制转换数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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