215

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

5 Answers 5

242

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.

9
  • 10
    How will that be stored in the DB? As a mongo datetime object?
    – Thilo
    Commented Sep 24, 2010 at 0:45
  • 3
    @Thilo: MongoDB has no special 'datetime' object as far as I know. It uses the JavaScript Date type, which is stored in BSON form. Commented Sep 24, 2010 at 8:04
  • 2
    @Thilo: Correct, that is basically the BSON representation of a JavaScript Date object. It's a 64-bit integer that stores the milliseconds since the Unix epoch and supports (most?) of the methods from the JavaScript specification. Commented Sep 25, 2010 at 6:16
  • 1
    @AboozarRajabi The 389 and 240 are the milliseconds of the timestamp. The Z in the string format tells MongoDB that the timestamp you provided is in UTC. If you then read it back, your application probably converts it to your local timezone, making it seem like the time has changed. But the time is still the same, it's only interpreted from a different timezone perspective. For example 12:50:42Z and 13:50:42+01:00 represent the same moment in time. Commented Mar 19, 2017 at 2:29
  • 5
    @AboozarRajabi In general you don't want to be concerned with how it is stored, as long as the initial input is correct. If it is 21:56:03+01:00 right now in CET and you insert new Date(), then MongoDB might represent it as 20:56:03Z. But when you read it back and display it in your application using local timezone settings (CET), it will read 21:56:03 again. Commented Mar 19, 2017 at 21:05
64

One datestamp is already in the _id object, representing insert time

So if the insert time is what you need, it's already there:

Login to 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:

> 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

I'm not really sold on this nosql mongodb is webscale stuff. Maybe it's faster, in some cases, for very large json objects in some contexts, but the syntax and usage is strange and annoying.

6
  • 33
    But it is the timestamp for when the document was saved in the db, sometimes you want to store dates and times not related to the insert date.
    – Yuval A.
    Commented Jan 27, 2015 at 14:14
  • 1
    If your database is really fast and two documents are stored in the same millisecond.. do those documents have the same _id?
    – Redsandro
    Commented May 23, 2015 at 12:02
  • 10
    @Redsandro no, but potentially they could have the same result of _id.getTimestamp().
    – kmiyashiro
    Commented Jun 12, 2015 at 22:45
  • @kmiyashiro, would you happen to know how to sort based on that timestamp?
    – ledlogic
    Commented Sep 28, 2015 at 5:41
  • 1
    Nevermind, sort({createdOn:-1); is the approach to use from stackoverflow.com/questions/28599237/…
    – ledlogic
    Commented Sep 28, 2015 at 5:54
2

I figured when you use pymongo, MongoDB will store the native Python datetime object as a Date field. This Date field in MongoDB could facilitate date-related queries later (e.g. querying intervals). Therefore, a code like this would work in Python

from datetime import datetime

datetime_now = datetime.utcnow()
new_doc = db.content.insert_one({"updated": datetime_now})

After this, I can see in my database a field like the following (I am using Mongo Compass to view my db). Note how it is not stored as a string (no quotation) and it shows Date as the field type.

enter image description here

Regarding javascript usage, this should also work there. As long as you have the +00:00 (UTC in my case) or Z at the end of your date, Javascript should be able to read the date properly with timezone information.

0

Use the code below to create a datetime variable that can be assigned in a document (Note that I'm creating a datetime object, not a date object):

from datetime import date
from datetime import datetime
import random

def random(date):
    my_year=random.randint(2020,2022)
    my_month=random.randint(1,12)
    my_day=random.randint(1,28)

    selected=datetime(year = my_year, month = my_month, day = my_day, hour = 0, minute = 0, second = 0)


def insert_objects(collection):

      collection.insert_one( { "mydate": random_date() })
0

BSON Date is a 64-bit integer that represents the number of milliseconds since the Unix epoch (Jan 1, 1970). This results in a representable date range of about 290 million years into the past and future.

The official BSON specification refers to the BSON Date type as the UTC datetime.

BSON Date type is signed. Negative values represent dates before 1970.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.