Dates ruby โ€‹โ€‹MongoDB

I have a collection with the on: created_at index (which in this particular case should be a date)

From rails, what is the right way to save a record and then get it by date?

I am trying something like:

Model: field: created_at ,: type => Time

script:

Col.create (: created_at => Time.parse (another_model.created_at) .to_s

and

Col.find (: all ,: conditions => {: created_at => Time.parse (same)})

and it returns nothing

+4
source share
2 answers

The Mongo driver and various ORMs handle Date, Time, and DateTime objects just fine; there is no reason to throw them in lines.

Col.create(:created_at => another_model.created_at) 

And find:

 Col.all(:created_at => another_model.created_at) 

You do not want to set strings because dates are stored inside the BSON Date object and are indexed and searched as such. If you save them as strings, you will not be able to efficiently perform actions such as more / less than comparison / range.

+3
source
 Col.create(:created_at => Time.parse(another_model.created_at).to_s) 

This string will pass your time object as a String, clear to_s to send it to the type parsing level in your ORM (MongoMapper or Mongoid) as a Time object. This is the only mistake I can see that will make it not work.

+1
source

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


All Articles