Mongodb aggregate: convert date to another timezone -
i save transaction :
{code: "a", total: 250000, timestamp: isodate("2016-01-20t23:57:05.771z")}, {code: "b", total: 300000, timestamp: isodate("2016-01-20t05:57:05.771z")}
each of transaction has timestamp
field under utc timezone in it. since live in jakarta (utc+7) timezone, need add 7 hours timestamp before aggregation. here's mongo syntax:
db.transaction.aggregate( [ { $project: { year: { $year: "$timestamp" }, month: { $month: "$timestamp" }, day: { $dayofmonth: "$timestamp" } } } ])
it returns:
{ "_id" : objectid("56a01ed143f2fd071793d63b"), "year" : 2016, "month" : 1, "day" : 20 }, { "_id" : objectid("56a01ed143f2fd071793d63b"), "year" : 2016, "month" : 1, "day" : 20 }
which wrong since first transaction (code a
), happened @ 21st january, since converted utc (-7 hours), became isodate("2016-01-20t23:57:05.771z")
note: i'm aware about same problem on here, here's i've been tried far:
db.transaction.aggregate( [ {$project: {"timestamp": {$add: [7 * 60 * 60 * 1000]}}}, { $project: { year: { $year: "$timestamp" }, month: { $month: "$timestamp" }, day: { $dayofmonth: "$timestamp" } } } ])
but returns can't convert bson type numberdouble date
error. suggestions?
you need add "timestamp" 7 * 60 * 60 * 1000
can in 1 $project
stage.
db.collection.aggregate([ { "$project": { "year": { "$year": { "$add": [ "$timestamp", 7 * 60 * 60 * 1000 ] } }, "month": { "$month": { "$add": [ "$timestamp", 7 * 60 * 60 * 1000 ] } }, "day": { "$dayofmonth": { "$add": [ "$timestamp", 7 * 60 * 60 * 1000 ] } } } } ])
which returns:
{ "_id" : objectid("56a07f8f8448ed9fd2359365"), "year" : 2016, "month" : 1, "day" : 21 } { "_id" : objectid("56a07f8f8448ed9fd2359366"), "year" : 2016, "month" : 1, "day" : 20 }
Comments
Post a Comment