6

我需要在 Mongoid 中创建一个命名范围,用于比较同一文档中的两个时间字段。如

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

这显然不起作用,因为它被视为:checked_at一个符号,而不是实际的字段。关于如何做到这一点的任何建议?

更新 1

这是我声明了这个范围的模型,去掉了很多额外的代码。

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

这给了我以下错误:

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

4

3 回答 3

8

据我所知,mongodb 不支持对动态值的查询。但是您可以使用 javascript 函数:

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

为了加快速度,您可以添加一个像“is_unresolved”这样的属性,当这个条件匹配时,它会在更新时设置为真(并索引)。

于 2010-10-13T19:56:30.870 回答
3
scope :foo, :where => {:updated_at.gt => self.checked_at}

例如,这将起作用:

scope :foo, where(:start_date.lte=>Date.today.midnight)
于 2010-09-25T20:52:27.680 回答
1

不确定您是否会喜欢这种方法,它不是最好的,但应该可以。

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

你用 User.unresolved(my_user_object) 调用它现在重读你的帖子后似乎这可能不会做你想要的。如果这是真的,那么您可能需要使用 MapReduce 或可能是 Baju 的方法(尚未测试过)

于 2010-10-14T07:43:59.753 回答