Date in Mongolian requests

I have a model:

class SimpleAction include Mongoid::Document field :set_date, :type => Date 

and I have some data in the collection:

{"_id": ObjectId ("4f6dd2e83a698b2518000006"), "name": "lost", "" notes ":" "," set_date (1i) ":" 2012 "," set_date (2i) ":" 3 ", "set_date (3i)": "25", "set_date (4i)": "13", "set_date (5i)": "57", "duration": 15, "todo": "4"}

You can see that the storage date of mongoid in five fields is set_date (ni).

I have two questions:

  • How to filter data by set_date field in mongo console client? Something like that:

     db.simple_actions.find({ set_date : { "$lte" : new Date() } }) 

    My request did not return any data.

  • How to filter data by set_date field in my Rails controller? Something like that:

     @simple_actions = SimpleAction.where(:set_date => { '$lte' => Date.today }) 
+6
source share
2 answers

I would recommend not using Date , but DateTime instead:

 field :set_date, :type => DateTime 

Now it will not only be saved in 1 field, for example:

 "set_date" : ISODate("2012-03-14T17:42:27Z") 

But Mongoid will correctly handle the various transformations for the queries as you want:

 SimpleAction.where( :set_date => { :$lte => Date.today } ) 
+13
source

You can use it with the Time class.

Rails is so good with Api for mobile (like Android) when you sent a date from mobile to Api, for example: 1482723520. (last_created = 1482723520)

You can use it like this:

  time = Time.at(params[:last_created].to_i) 

And in Rails, you can query like this:

 Number.where(created_at: { :$gte => time }) 
0
source

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


All Articles