I have a mongodb collection where each document has some attributes and a utc timestamp. I need to pull out data from the collection and use the aggregation framework becaus
Every approach suggested above works perfectly fine, but since there is a new version of mongodb, from 2.6 you can use $let in the aggregation framework, this will let you create variables on the fly, thus avoiding the need to $project before grouping. Now you could create a variable with $let that will hold the localized time, and use it in the $group operator.
Something like:
db.test.aggregate([
{$group: {
_id: {
$let: {
vars: {
local_time: { $subtract: ["$date", 10800000]}
},
in: {
$concat: [{$substr: [{$year: "$$local_time"}, 0, 4]},
"-",
{$substr: [{$month: "$$local_time"}, 0, 2]},
"-",
{$substr: [{$dayOfMonth: "$$local_time"}, 0, 2]}]
}
}
},
count: {$sum: 1}
}
}])
Notice that you use $let inside definition of a block/variable, and the value of that block/variable is the returned value of the subexpression "in", where the above defined vars are used.