在mongodb中存储日期/时间的最佳方式 [英] Best way to store date/time in mongodb
问题描述
我已经看到使用字符串,整数时间戳和mongo datetime对象。
最好的方法是存储本机JavaScript Date对象,其映射到 BSON native Date对象。
> db.test.insert({date:ISODate()})
> db.test.insert({date:new Date()})
> db.test.find()
{_id:ObjectId(...),date:ISODate(2014-02-10T10:50:42.389Z)}
{ _id:ObjectId(...),date:ISODate(2014-02-10T10:50:57.240Z)}
本机类型支持开箱即用的有用方法的整个范围,您可以在map-reduce作业中使用它。 p>
如果需要,您可以轻松地将 Date
对象转换为Unix时间戳 1),分别使用 getTime()
方法和 Date(milliseconds)
构造函数。
1)严格来说,Unix时间戳是在秒中测量的。自Unix纪元以来,JavaScript Date对象在 milliseconds 中测量。
I've seen using strings, integer timestamps and mongo datetime objects.
The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.
> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }
The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.
If you need to, you can easily convert Date
objects to and from Unix timestamps1), using the getTime()
method and Date(milliseconds)
constructor, respectively.
1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.
这篇关于在mongodb中存储日期/时间的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!