Skip to content
Advertisement

MongoDB/Python – Date in collection (to use for query)

I just started using mongoDB (Version 3.6.8) today, and I like it.

I was reading that it should be possible to have a date object directly in the database, but I can’t get it to work.

Also I was wondering if it is the best solution or if I should just store my dates as “Epoch millis” instead?

I am trying to use use the $dateFromString keyword which should work but i receive this error:

JavaScript

My code looks like this:

JavaScript

The reason why I need something like a date-object in the database is because I want to do a conditional query on the data, so that the database only sends the data i require. So i expect to do something like this.

JavaScript

But when I do this the app prints nothing.

Advertisement

Answer

The $dateFromString is an operator for MongoDB aggregations. An aggregation is a powerful way to create complex queries in MongoDB. Hence, this might not be what you need.

I would recommend storing the dates in the normal format. So your code should look something like this:

JavaScript

If you are concerned about timezones, MongoDB stores each date in UTC by default, converting whatever timezone is specified in your date to UTC. When reading the dates, you can then convert them to whatever timezone you need.

EDIT: When writing your query, try using an actual date object. This converts the query date to an actual ISO date that the DB can understand.

JavaScript

If you’re trying to find entries that fall within a date range, you can do something like:

JavaScript
Advertisement