Best way to store date/time in mongodb

DatetimeDateMongodb

Datetime Problem Overview


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

Datetime Solutions


Solution 1 - Datetime

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.

Solution 2 - Datetime

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

Solution 3 - Datetime

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.

Solution 4 - Datetime

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionxradoView Question on Stackoverflow
Solution 1 - DatetimeNiels van der RestView Answer on Stackoverflow
Solution 2 - DatetimeEric LeschinskiView Answer on Stackoverflow
Solution 3 - DatetimeHossein KalbasiView Answer on Stackoverflow
Solution 4 - DatetimeDrorView Answer on Stackoverflow