Best way to store date/time in mongodb

Viewed 227159

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

4 Answers

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.

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