Mongodb时间戳(以毫秒为单位)

问题描述:

我已将日期以unix时间戳格式存储在mongodb中>> 1449060622 现在我也想添加毫秒,以便在同一秒插入的记录可以正确排序.

I have stored date in unix timestamp format in mongodb >> 1449060622 now I want to add milliseconds as well so if records inserted in same seconds can be sorted properly.

有人可以建议我使用js new Date()更好或更简单(new Date).getTime()吗?

can someone suggest me that using js new Date() is more better or simply (new Date).getTime() ?

无论何时将时间存储在MongoDB中,您都应该真正考虑使用本机Date类型.它不仅可以为您提供毫秒级的精度,而且还可以解锁许多简单整数无法使用的功能,例如日期聚合运算符.

Whenever you store times in MongoDB you should really consider using the native Date type instead. Not only does it provide you with millisecond precision, it also unlocks a lot of features which are unavailable for simple integer, like date aggregation operators for example.

如果您确实出于某些晦涩的原因不想使用本地日期(我想不出一个好的日期),或者不想转换整个数据库(确实应该),并且需要更高的精度,您可以考虑将新值添加为浮点值.这样可以确保与旧数据的互操作性,因为整数和浮点值通常可以轻松转换并相互比较.

If you really don't want to use native dates for some obscure reason (I couldn't think of a good one) or don't want to convert your whole database (really, you should) and need a higher precision, you might consider to add new values as floating point values. This ensures interoperability with the old data because integers and floating point values usually can be converted and compared between each other easily.