Mongoid Date Time Range queries

988 views
Skip to first unread message

rtdp

unread,
Jul 22, 2011, 2:22:04 AM7/22/11
to Mongoid
I am running in very strange date range query problem. When I use
DateTime.now.utc option to query database, the query date for
DateTime.now is different that my current DateTime.now(i.e. one that's
returned on console.)

My mogoid.yml uses-
use_utc: true

I have my named scope like this -

scope :running_auctions, {
:where => { :end_time.gt => DateTime.now.utc },
:order_by => [:end_time, "ASC"]
}

And on console I can do this -

Loading development environment (Rails 3.0.7)
irb(main):001:0> Auction.running_auctions
=> #<Mongoid::Criteria
selector: {:end_time=>{"$gt"=>Fri Jul 22 00:42:38 UTC 2011}},
options: {:sort=>[:end_time, "ASC"]},
class: Auction,
embedded: false>

Notice that my date here is Fri Jul 22 00:42:38 UTC 2011

irb(main):002:0> DateTime.now
=> Fri, 22 Jul 2011 11:42:56 +0530

irb(main):003:0> DateTime.now.utc
=> Fri, 22 Jul 2011 06:12:59 +0000

Notice here that my datetime is Fri, 22 Jul 2011 06:12:59 +0000

What is making query date older than actual current date ? Does mogoid
or mongodb doing caching there ?
Please let me know if I am missing something.

Nick Hoffman

unread,
Jul 22, 2011, 8:21:47 AM7/22/11
to mon...@googlegroups.com
This is because the DateTime.now.utc in the scope is evaluated when the class is loaded. You need DateTime.now.utc to be evaluated each time the scope is executed. Eg:

scope :running_auctions, lambda { :where => {
  :end_time.gt => DateTime.now.utc,
  :order_by => [:end_time, :asc]
} }

Nick Hoffman

unread,
Jul 22, 2011, 8:33:55 AM7/22/11
to mon...@googlegroups.com
I've opened an issue in the mongoid-site project to get this documented:
https://github.com/mongoid/mongoid-site/issues/79
Reply all
Reply to author
Forward
0 new messages