在 mongodb 中存储日期/时间的最佳方式 [英] Best way to store date/time in mongodb

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

问题描述

我见过使用字符串、整数时间戳和 mongo datetime 对象.

I've seen using strings, integer timestamps and mongo datetime objects.

推荐答案

最好的方法是存储原生 JavaScript Date 对象,映射到 BSON 原生日期对象.

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") }

原生类型支持一系列开箱即用的有用方法,例如,您可以在 map-reduce 作业中使用这些方法.

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.

如果需要,您可以使用 getTime() 方法轻松地将 Date 对象与 Unix 时间戳进行相互转换1)Date(milliseconds) 构造函数,分别.

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) 严格来说,Unix 时间戳以为单位.JavaScript Date 对象以 毫秒为单位,自 Unix 纪元以来.

1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.

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

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