在 mongodb 中存储日期/时间的最佳方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3778428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to store date/time in mongodb
提问by xrado
I've seen using strings, integer timestamps and mongo datetime objects.
我见过使用字符串、整数时间戳和 mongo datetime 对象。
回答by Niels van der Rest
The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.
最好的方法是存储本机 JavaScript Date 对象,这些对象映射到BSON 本机 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") }
The native type supports a whole range of useful methodsout of the box, which you can use in your map-reduce jobs, for example.
本机类型支持一系列开箱即用的有用方法,例如,您可以在 map-reduce 作业中使用这些方法。
If you need to, you can easily convert Date
objects to and from Unix timestamps1), using the getTime()
method and Date(milliseconds)
constructor, respectively.
如果需要,您可以分别使用方法和构造函数轻松地将Date
对象与 Unix 时间戳1) 相互转换。getTime()
Date(milliseconds)
1)Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in millisecondssince the Unix epoch.
1)严格来说,Unix 时间戳以秒为单位。JavaScript Date 对象以 Unix 纪元以来的毫秒为单位。
回答by Eric Leschinski
One datestamp is already in the _id object, representing insert time
_id 对象中已经有一个日期戳,代表插入时间
So if the insert time is what you need, it's already there:
因此,如果插入时间是您所需要的,那么它已经存在:
Login to mongodb shell
登录mongodb shell
ubuntu@ip-10-0-1-223:~$ mongo 10.0.1.223
MongoDB shell version: 2.4.9
connecting to: 10.0.1.223/test
Create your database by inserting items
通过插入项目创建数据库
> db.penguins.insert({"penguin": "skipper"})
> db.penguins.insert({"penguin": "kowalski"})
>
Lets make that database the one we are on now
让该数据库成为我们现在使用的数据库
> use penguins
switched to db penguins
Get the rows back:
取回行:
> db.penguins.find()
{ "_id" : ObjectId("5498da1bf83a61f58ef6c6d5"), "penguin" : "skipper" }
{ "_id" : ObjectId("5498da28f83a61f58ef6c6d6"), "penguin" : "kowalski" }
Get each row in yyyy-MM-dd HH:mm:ss format:
以 yyyy-MM-dd HH:mm:ss 格式获取每一行:
> db.penguins.find().forEach(function (doc){ d = doc._id.getTimestamp(); print(d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds()) })
2014-12-23 3:4:41
2014-12-23 3:4:53
If that last one-liner confuses you I have a walkthrough on how that works here: https://stackoverflow.com/a/27613766/445131
如果最后一行让你感到困惑,我有一个关于它是如何工作的演练:https: //stackoverflow.com/a/27613766/445131