Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoid named scope comparing two time fields in the same document

I need to create a named scope in Mongoid that compares two Time fields within the same document. Such as

scope :foo, :where => {:updated_at.gt => :checked_at}

This obviously won't work as it treats :checked_at as a symbol, not the actual field. Any suggestions on how this can be done?

Update 1

Here is my model where I have this scope declared, with a lot of extra code stripped out.

class User
  include Mongoid::Document
  include Mongoid::Paranoia
  include Mongoid::Timestamps

  field :checked_at, :type => Time

  scope :unresolved, :where => { :updated_at.gt => self.checked_at }
end

This gives me the following error:

'<class:User>': undefined method 'checked_at' for User:Class (NoMethodError)

like image 447
Jey Balachandran Avatar asked Sep 25 '10 18:09

Jey Balachandran


3 Answers

As far as I know, mongodb doesn't support queries against dynamic values. But you could use a javascript function:

scope :unresolved, :where => 'this.updated_at >= this.checked_at'

To speed this up you could add an attribute like "is_unresolved" which will be set to true on update when this condition is matched ( and index that ).

like image 155
Baju Avatar answered Nov 01 '22 13:11

Baju


scope :foo, :where => {:updated_at.gt => self.checked_at}

For example, this will work:

scope :foo, where(:start_date.lte=>Date.today.midnight)
like image 33
Jesse Wolgamott Avatar answered Nov 01 '22 11:11

Jesse Wolgamott


Not sure if you'll like this method, it's not the best, but it should work.

class User
  include Mongoid::Document
  include Mongoid::Paranoia
  include Mongoid::Timestamps

  field :checked_at, :type => Time

  scope :unresolved, lambda{ |user| where(:updated_at.gt => user.checked_at) }
end

You call it with User.unresolved(my_user_object) It seems now after rereading your post that this probably won't do what you want. If this is true, then you will probably need to use MapReduce or possibly Baju's method (have not tested it)

like image 37
Preston Marshall Avatar answered Nov 01 '22 13:11

Preston Marshall