What is the best way to format date in JSON for Mongo DB storage

I have a date with time. I use ruby, but the language does not matter.

d = "2010-04-01 13:00:00"

What is the best way to format this date for Mongo DB? β€œBetter,” I mean, is there a specific format that I could use when Mongo recognized it as a date and could give me more advanced filters for filtering?

i.e.: If formatted correctly, can I ask Mongo to return all records whose month is "04"?

Thanks!

+4
source share
3 answers

You do not need to format dates at all; Dates - Supported data type. Each client driver must support dates through its standard date type, including ruby one .

For advanced queries like your example, you can use the javascript expression for the find qualifier:

{"$where": "this.date.getMonth() == 3"} 
+3
source

In ruby, you should use a Time instance that will be stored as the BSON date and time type. You can use the $ where clause, such as Coady, but it would be better to do a range query with $ lt and $ gt-less overhead and can use an index.

+1
source

I don't like relying on Date Mongo objects. I think Mongo is slower with 'date' objects than with other data types (like integers).

I usually use integers (if you need a time zone, you also have a tz field, then you have localized time):

 document = {:some_timestamp => Time.now.to_i} @collection.find({'some_timestamp' => {'$gte' => Time.now.to_i}}) 

Sometimes I just use the timestamp built into BSON :: ObjectId's:

 id = BSON::ObjectId.from_time(Time.now) @collection.find({'_id' => {'$lte' => id}}) 
0
source

Source: https://habr.com/ru/post/1305785/


All Articles