ChatGPT解决这个技术问题 Extra ChatGPT

Best way to store date/time in mongodb

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


D
Dan Dascalescu

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.


How will that be stored in the DB? As a mongo datetime object?
@Thilo: MongoDB has no special 'datetime' object as far as I know. It uses the JavaScript Date type, which is stored in BSON form.
@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.
@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.
@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.
E
Eric Leschinski

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


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.
If your database is really fast and two documents are stored in the same millisecond.. do those documents have the same _id?
@Redsandro no, but potentially they could have the same result of _id.getTimestamp().
@kmiyashiro, would you happen to know how to sort based on that timestamp?
Nevermind, sort({createdOn:-1); is the approach to use from stackoverflow.com/questions/28599237/…
H
Hossein Kalbasi

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.

https://i.stack.imgur.com/rXl8X.png

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.


D
Dror

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