我有在MongoDB中以UTC时间格式插入的数据。我想要根据时区转换时间。在mongo查询中是否有可能这样做?Mongo查询中的时区
回答
我们考虑您的文档如下包含ISODate
:
db.collection.insert({"date":new Date()})
上面的查询插入date
在ISODate
格式现在你想这个ISODate
转换成给timeZone
。
假设您想将上述日期转换为Eastern Daylight Saving Time (EDT)
epoch time zone conertor然后offset
转换为14400 * 1000
。首先将ISODate
转换为timeStamp
,然后使用substract
EDT偏移in
时间戳and then convert
时间戳to
ISODate`再次。
检查下面聚集的查询:
db.collection.aggregate({
"$project": {
"timestamp": { //convert ISODate tom timestamp
"$subtract": [{
"$divide": [{
"$subtract": ["$date", new Date("1970-01-01")]
}, 1000]
}, {
"$mod": [{
"$divide": [{
"$subtract": ["$date", new Date("1970-01-01")]
}, 1000]
}, 1]
}]
}
}
}, {
"$project": {
"timeZoneTimeStamp": {
"$subtract": [{ //substract timestamp to given offset if offset will in postive then replace subtract to add
"$multiply": ["$timestamp", 1000]
}, 14400000]
}
}
}, {
"$project": {
"timeZoneTimeStamp": 1, //converted timeZoneTimeStamp if required
"_id": 0,
"newDate": { // newDate is converted timezone ISODate
"$add": [new Date(0), "$timeZoneTimeStamp"]
}
}
})
注: 在上述查询转换从ISODATE
到timeStamp
ref. here
也可以在这里看到类似的答案:http://stackoverflow.com/a/31354088/404699 – steampowered
在情况下,如果日期不改变,例如恒定就像created_record_date那么无论你需要哪个时区数据,你都应该预先计算并保存(如字符串)和同一个文档,这样你就不必在运行时运行巨大的处理,这可能会减慢执行时间。如果您有现有记录并且想要将各种不同的时区数据与记录一起存储,请考虑运行Map-Reduct作业并分别更新文档。 (让我知道如果你需要的代码)。但是,如果此日期字段可以根据业务逻辑进行更改,那么它在运行时是明智的。这两种技术都有其不同的使用案例及其优缺点。
- 3.6时区已添加$
- 1. 如何使用具有时区的时间戳查询Mongo?
- 2. 在javascript中的Mongo查询
- 3. 在python中的mongo查询
- 4. Arraylist中的Mongo DB查询
- 5. 更新中的Mongo查询
- 6. mongo objectid'contains'查询
- 7. Python Mongo:在查询中使用'$或'mongo
- 8. 用Ruby/Javascript查询Mongo组中的计数结果的区别
- 9. 在mongo的时间范围内查询
- 10. 如何在Mongo中查询?
- 11. Mongo查询在mongo shell中运行,但不在bash mongo中--eval?
- 12. 如何在运行fluent-mongo时获得“真正的”mongo查询
- 13. 调整Mongo查询
- 14. 嘲讽mongo查询
- 15. mongo慢查询,cursor.refresh?
- 16. Mongo文档查询
- 17. 用mongo python查询
- 18. Mongo查询查找年数
- 19. MySQL时区查询
- 20. 简单的mongo查询
- 21. 带投影的Mongo查询
- 22. 查询的Mongo索引
- 23. 用spring mongo查询oplog时间戳
- 24. 将mongo查询翻译成php mongo
- 25. Mongo:从多个查询中查找
- 26. 从MySQL查询生成Mongo查询
- 27. Spring Mongo Group通过GroupBy查询查询
- 28. 用Spring Data查询所有mongo查询
- 29. 锂电池中的Mongo查询
- 30. 数组查询中的Mongo数组
送你想提那些 – Aman
我的格式和格式在2015年6月25日搜索记录。我有记录在日期2015-06-24 24:17:51。在查询时,此记录A必须根据时区进行转换并获得列表。 – user3702039
是'timeZone'保存在文档中还是外部传递的? – Yogesh