How to deal with the timezone issue when storing dates in utc using mongod?

前端 未结 4 897
予麋鹿
予麋鹿 2020-12-01 01:57

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

4条回答
  •  粉色の甜心
    2020-12-01 02:30

    Aside from the SERVER-6310 mentioned by Matt Johnson, one other workaround is to use the $project operator to add or subtract from the UTC time zone to "shift the time" into the correct local zone. Turns out you can add or subtract time in milliseconds.

    For example, assuming I have a Date field called orderTime. I'd like to query for EDT. That is -4 hours from UTC. That's 4 * 60 * 60 * 1000 milliseconds.

    So I would then write the following projection to get day_ordered in local time for all my records:

    db.table.aggregate( 
        { $project : { orderTimeLocal : { $subtract : [ "$orderTime", 14400000] } } },
        { $project : { day_ordered : { $dayOfYear : "$orderTimeLocal" } } })
    

提交回复
热议问题