Is it possible to type cast data inside an aggregation pipeline on MongoDB?

删除回忆录丶 提交于 2020-01-01 09:33:28

问题


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

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

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?


回答1:


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


来源:https://stackoverflow.com/questions/21701292/is-it-possible-to-type-cast-data-inside-an-aggregation-pipeline-on-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!