我用类似的东西保存我的交易:
{code: "A", total: 250000, timestamp: ISODate("2016-01-20T23:57:05.771Z")},
{code: "B", total: 300000, timestamp: ISODate("2016-01-20T05:57:05.771Z")}
每笔交易在 UTC 时区下都有 timestamp
字段。由于我住在 Jakarta (UTC+7) 时区,因此我需要在聚合之前将 7 小时添加到我的时间戳。这是我的 mongo 语法:
db.transaction.aggregate(
[
{
$project:
{
year: { $year: "$timestamp" },
month: { $month: "$timestamp" },
day: { $dayOfMonth: "$timestamp" }
}
}
])
返回:
{
"_id" : ObjectId("56a01ed143f2fd071793d63b"),
"year" : 2016,
"month" : 1,
"day" : 20
},
{
"_id" : ObjectId("56a01ed143f2fd071793d63b"),
"year" : 2016,
"month" : 1,
"day" : 20
}
自从第一次交易(代码 A
)发生在 1 月 21 日以来是错误的,但是由于它被转换为 UTC(-7 小时),它变成了 ISODate("2016 -01-20T23:57:05.771Z")
注意:我知道 about the same problem over here ,这是我迄今为止尝试过的:
db.transaction.aggregate(
[
{$project: {"timestamp": {$add: [7 * 60 * 60 * 1000]}}},
{
$project:
{
year: { $year: "$timestamp" },
month: { $month: "$timestamp" },
day: { $dayOfMonth: "$timestamp" }
}
}
])
但它返回 can't convert from BSON type NumberDouble to Date
错误。
有什么建议吗?
最佳答案
作为更新,MongoDB 3.6 具有一个新的时区参数,用于在聚合框架中进行日期操作。大多数与日期相关的运算符都接受这个可选参数,见 $hour举个例子。
例如,如果我们有一个文档,其中日期正好是 UTC 中的新年:
> db.test.find()
{"_id": 1, "dt": ISODate("2018-01-01T00:00:00Z")}
我们可以在纽约时区显示日期:
> db.test.aggregate([
... {$project:{
... date:{$dayOfMonth:{date:'$dt',timezone:'America/New_York'}},
... month:{$month:{date:'$dt',timezone:'America/New_York'}},
... year:{$year:{date:'$dt',timezone:'America/New_York'}},
... hour:{$hour:{date:'$dt',timezone:'America/New_York'}}
... }}
... ])
{ "_id": 1, "date": 31, "month": 12, "year": 2017, "hour": 19 }
我们还可以在悉尼时区显示日期:
> db.test.aggregate([
... {$project:{
... date:{$dayOfMonth:{date:'$dt',timezone:'Australia/Sydney'}},
... month:{$month:{date:'$dt',timezone:'Australia/Sydney'}},
... year:{$year:{date:'$dt',timezone:'Australia/Sydney'}},
... hour:{$hour:{date:'$dt',timezone:'Australia/Sydney'}}
... }}
... ])
{ "_id": 1, "date": 1, "month": 1, "year": 2018, "hour": 11 }
时区描述使用标准 Olson Timezone Identifier string .
关于MongoDB聚合: convert date to another timezone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34914737/