Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • How can I filter data by set_date field in the mongo console client? Something like this:

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

    My query didn't return any data.

  • How can I filter data by set_date field in my Rails controller? Something like this:

    @simple_actions = SimpleAction.where(:set_date => { '$lte' => Date.today })
    
like image 287
ceth Avatar asked Mar 24 '12 14:03

ceth


1 Answers

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 } )
like image 134
rfunduk Avatar answered Oct 21 '22 13:10

rfunduk