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

前端 未结 4 910
予麋鹿
予麋鹿 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:50

    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.

提交回复
热议问题