mongodb聚合函式時間分組問題
阿新 • • 發佈:2019-02-17
mongodb聚合函式時間如果是date型別的 分組的話會出現時區相差8小時問題,因為$dayOfYear等函式是按照utc時間分組的 所以會有問題,
解決方法1:
時間地段用字串儲存,然後利用$substr來擷取 年月日進行按天分組等 程式碼如下
db.main_test.aggregate( { $project: { time: '$time', timeFormat: { $dateToString: { format: "%Y-%m-%d", date: "$time" } }, timeYearStr: { $substr: ['$time', 0, 4] }, timeMonthStr: { $substr: ['$time', 5, 2] }, timeDayStr: { $substr: ['$time', 8, 2] }, year: { $year: "$time" }, month: { $month: "$time" }, day: { $dayOfMonth: "$time" }, request: '$request' } }, { $match: { time: { $gte: new Date('2017-03-13'), $lte: new Date('2017-03-15') } } }, { $group: { _id: { year: '$year', month: '$timeMonthStr', day: '$timeDayStr' }, time: { $last: "$time" }, timeFormat: { $last: "$timeFormat" }, timeYearStr: { $last: "$timeYearStr" }, timeMonthStr: { $last: "$timeMonthStr" }, timeDayStr: { $last: "$timeDayStr" }, totalReq: { $sum: "$request" } } }, { $sort: { time: 1 } } )
解決方法2:時間還是date型別 使用 $add:['$time',28800000]後再進分組
如下:
db.main_test.aggregate( { $project: { time: '$time', timeNew: { $substr:[{$add:['$time',28800000]},0,10]}, timeFormat: { $dateToString: { format: "%Y-%m-%d", date: "$time" } }, timeYearStr: { $substr: ['$time'.toLocaleString(), 0, 4] }, timeMonthStr: { $substr: ['$time', 5, 2] }, timeDayStr: { $substr: ['$time', 8, 2] }, year: { $year: "$time" }, month: { $month: "$time" }, day: { $dayOfMonth: {$add:['$time',28800000]} }, request: '$request' } }, { $match: { time: { $gte: new Date('2017-03-13'), $lte: new Date('2017-03-15') } } }, { $group: { _id: { year: '$year', month: '$timeMonthStr', day: '$day' }, day:{$last:'$day'}, timeNew:{$last:'$timeNew'}, time: { $last: "$time" }, timeFormat: { $last: "$timeFormat" }, timeYearStr: { $last: "$timeYearStr" }, timeMonthStr: { $last: "$timeMonthStr" }, timeDayStr: { $last: "$timeDayStr" }, totalReq: { $sum: "$request" } } }, { $sort: { time: 1 } } )
參考連結:https://docs.mongodb.com/manual/reference/operator/aggregation/substr/