Can casting data be entered into the aggregation pipeline on MongoDB?

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 finally concatenate the day , mon and year fields into a date string in the application. However, for many reasons, sometimes I want to concatenate fields before exiting the database, so I first 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 will not work because $concat expects strings and day , mon and year be integers. So my question is: can I type a field using the $project operation?

+7
mongodb aggregation-framework
source share
1 answer

Yes , you can use $substr to translate a number into a string. Your missing link will look like this:

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

All Articles