本文介绍了在 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 原生使用的存储数据格式)有一个 专用日期类型 UTC 日期时间 这是一个 64 位(因此,8 字节)有符号整数,表示自 Unix 时间纪元以来的毫秒数.使用任何其他类型来存储日期和时间戳的正当理由很少.

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 字节二进制 blobit 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.

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 中存储日期的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 21:37