ceth
ceth

Reputation: 45295

Date in Mongoid queries

I have a model:

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

and I have some data in 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 mongoid store date in the five fields - set_date(ni).

I have two question:

Upvotes: 8

Views: 11740

Answers (2)

ThienSuBS
ThienSuBS

Reputation: 1622

You can use it with class Time.

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

You can use it like that:

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

And in Rails you can query like that:

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

Upvotes: 0

rfunduk
rfunduk

Reputation: 30442

I would recommend not using Date, but instead DateTime:

field :set_date, :type => DateTime

Now not only will it be stored in 1 field, like so:

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

But Mongoid will correctly handle various conversions for queries like you want:

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

Upvotes: 15

Related Questions