Is it possible to type cast data inside an aggrega

2020-07-09 09:38发布

问题:

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