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?
mongodb aggregation-framework
Rafael S. Calsaverini
source share