211

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

Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
xrado
  • 2,710
  • 3
  • 22
  • 20

5 Answers5

239

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.

Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
Niels van der Rest
  • 31,664
  • 16
  • 80
  • 86
  • 9
    How will that be stored in the DB? As a mongo datetime object? – Thilo Sep 24 '10 at 00: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. – Niels van der Rest Sep 24 '10 at 08: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](http://w3schools.com/jsref/jsref_obj_date.asp). – Niels van der Rest Sep 25 '10 at 06:16
  • In the mongo shell `ISODate()` and `new Date()` evaluate to be the same. What's up the with that? – gh0st Dec 21 '16 at 22:08
  • @NielsvanderRest What's the meaning of 389Z and 240Z? And, how can I insert my own date and time? When I insert something like `ISODate("2013-12-10T11:50:57Z")`, it changes the time! – Aboozar Rajabi Mar 18 '17 at 09:00
  • 1
    @AboozarRajabi The `389` and `240` are the milliseconds of the timestamp. The `Z` in the [string format](http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15) 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. – Niels van der Rest Mar 19 '17 at 02:29
  • @NielsvanderRest As my local timezone is Central European Time (CET) and I want to store using my local timezone, I should use this format: `HH:MM:SS+01:00`. Am I right? – Aboozar Rajabi Mar 19 '17 at 11:20
  • 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. – Niels van der Rest Mar 19 '17 at 21:05
  • @dan how to store different timezone date in one collection and after that we apply filter on it suppose there is a appoint main global app using common db and two user one from the India and other from UK and store there appointment time but monodb save date in ISOdate format how to I achieve my goal – Priyanka Sankhala Apr 14 '20 at 16:14
62

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

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
  • 32
    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. Jan 27 '15 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 May 23 '15 at 12:02
  • 10
    @Redsandro no, but potentially they could have the same result of `_id.getTimestamp()`. – kmiyashiro Jun 12 '15 at 22:45
  • @kmiyashiro, would you happen to know how to sort based on that timestamp? – ledlogic Sep 28 '15 at 05:41
  • 1
    Nevermind, sort({createdOn:-1); is the approach to use from http://stackoverflow.com/questions/28599237/sorting-timestamp-in-descending-order-in-mongodb – ledlogic Sep 28 '15 at 05:54
  • Here's how MongoDB generates IDs: https://docs.mongodb.com/manual/reference/method/ObjectId/ . Note that it's not exclusively generated from the creation timestamp (timestamp is just the first 4 bytes). – diazdeteran Jan 24 '17 at 15:27
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.

Hossein Kalbasi
  • 1,641
  • 2
  • 13
  • 26
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() })
Dror
  • 5,107
  • 3
  • 27
  • 45
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.

Omid
  • 1
  • 2