gpt4 book ai didi

node.js - 在 mongodb 本地时区聚合

转载 作者:IT老高 更新时间:2023-10-28 13:15:56 27 4
gpt4 key购买 nike

我正在构建将在意大利使用的 mongodb 和 nodejs 应用程序。意大利时区是 +02:00 。这意味着如果有人在 7 月 11 日凌晨 1 点保存一些数据,那么它将被保存为 7 月 10 日晚上 11:00,因为 mongo 以 UTC 保存日期。我们需要显示日期明智的 tx 计数。所以我按日期查询分组。但它显示前一天的交易。应该有什么解决方法。

> db.txs.insert({txid:"1",date : new Date("2015-07-11T01:00:00+02:00")})

> db.txs.insert({txid:"2",date : new Date("2015-07-11T05:00:00+02:00")})

> db.txs.insert({txid:"3",date : new Date("2015-07-10T21:00:00+02:00")})

> db.txs.find().pretty()

{
"_id" : ObjectId("55a0a55499c6740f3dfe14e4"),
"txid" : "1",
"date" : ISODate("2015-07-10T23:00:00Z")
}
{
"_id" : ObjectId("55a0a55599c6740f3dfe14e5"),
"txid" : "2",
"date" : ISODate("2015-07-11T03:00:00Z")
}
{
"_id" : ObjectId("55a0a55699c6740f3dfe14e6"),
"txid" : "3",
"date" : ISODate("2015-07-10T19:00:00Z")
}

> db.txs.aggregate([
{ $group:{
_id: {
day:{$dayOfMonth:"$date"},
month:{$month:"$date"},
year:{$year:"$date"}
},
count:{$sum:1}
}}
])

{ "_id" : { "day" : 11, "month" : 7, "year" : 2015 }, "count" : 1 }
{ "_id" : { "day" : 10, "month" : 7, "year" : 2015 }, "count" : 2 }

它在 7 月 10 日显示 2 笔交易,在 7 月 11 日显示 1 笔交易。但是我们需要显示 7 月 11 日的 2 笔交易和 7 月 10 日的 1 笔交易。

实际上是在意大利的 7 月 11 日

db.txs.insert({txid:"1",date : new Date("2015-07-11T01:00:00+02:00")})

发生但 mongo 将日期存储为:

ISODate("2015-07-10T23:00:00Z")

最佳答案

在 mongo 版本 3.6 中添加了时区,mongo doc

用时区提取日期部分的表达式是

{ date: <dateExpression>, timezone: <tzExpression> }

我们可以在获取日期部分时指定时区或偏移量

管道

> db.txs.aggregate([
... { $group:{
... _id: {
... day: {$dayOfMonth: {date :"$date", timezone : "Europe/Rome"}}, // timezone
... month: {$month: {date : "$date", timezone : "+02:00"}}, //offset
... year: {$year: {date : "$date", timezone : "+02:00"}} //offset
... },
... count:{$sum:1}
... }}
... ])

结果

{ "_id" : { "day" : 10, "month" : 7, "year" : 2015 }, "count" : 1 }
{ "_id" : { "day" : 11, "month" : 7, "year" : 2015 }, "count" : 2 }
>

timezone 的列表|

关于node.js - 在 mongodb 本地时区聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31353740/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com