在MongoDB中存储日期的最佳方法是什么? [英] What is the best way to store dates in MongoDB?

查看:951
本文介绍了在MongoDB中存储日期的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习MongoDB,并希望从MySQL慢慢迁移.

I am just starting to learn about MongoDB and hoping to slowly migrate from MySQL.

在MySQL中,有两种不同的数据类型-DATE ('0000-00-00')DATETIME ('0000-00-00 00:00:00').在我的MySQL中,我使用DATE类型,但是我不确定如何将它们传输到MongoDB中.在MongoDB中,有一个Date对象,它与DATETIME类似.似乎最适合使用Date对象,但这将浪费空间,因为未使用小时,分钟,秒.另一方面,将日期存储为字符串似乎是错误的.

In MySQL, there are two different data types - DATE ('0000-00-00') and DATETIME ('0000-00-00 00:00:00'). In my MySQL, I use the DATE type, but I am not sure how to transfer them into MongoDB. In MongoDB, there is a Date object, which is comparable to DATETIME. It seems it would be most appropriate to use Date objects, but that would be wasting space, since hours, min, sec are not utilized. On the other hand, storing dates as strings seems wrong.

在MongoDB中存储日期('0000-00-00')是否有黄金标准?

Is there a golden standard on storing dates ('0000-00-00') in MongoDB?

推荐答案

BSON(mongo本地使用的存储数据格式)具有

BSON (the storage data format used by mongo natively) has a dedicated date type UTC datetime which is a 64 bit (so, 8 byte) signed integer denoting milliseconds since Unix time epoch. There are very few valid reasons why you would use any other type for storing dates and timestamps.

如果您迫切希望每个日期保存几个字节(同样,使用mongo的填充和最小块大小,并且这一切仅在极少数情况下值得解决),您可以通过将日期存储为3字节二进制blob来进行存储它作为YYYYMMDD格式的无符号整数,或2字节的二进制斑点表示天自X年1月1日",其中X必须因为这样适当地选择只支持一个时间范围跨越179年.

If you're desperate to save a few bytes per date (again, with mongo's padding and minimum block size and everything this is only worth the trouble in very rare cases) you can store dates as a 3 byte binary blob by storing it as an unsigned integer in YYYYMMDD format, or a 2 byte binary blob denoting "days since January 1st of year X" where X must be chosen appropriately since that only supports a date range spanning 179 years.

正如下面的讨论所示,这仅是在非常罕见的情况下可行的方法. 基本上;使用mongo的本地日期类型;)

As the discussion below demonstrates this is only a viable approach in very rare circumstances. Basically; use mongo's native date type ;)

这篇关于在MongoDB中存储日期的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆