Ruby Mongo驱动程序:如何查找日期间隔?

时间:2011-05-11 19:35:21

标签: ruby-on-rails-3 mongodb mongodb-ruby

鉴于初始日期和今天,在该日期之间搜索所有“名称”的查询是什么?

谢谢

1 个答案:

答案 0 :(得分:7)

<强> MongoMapper

您应该能够使用MongoMapper的查询运算符。假设您的“用户”模型具有“created_on”日期,您可以使用它来获取名称。 (我相信MongoDB使用UTC Times存储所有日期/时间对象):

initial_date = Time.utc(2011, 5, 1) # 2011-05-01 00:00:00 UTC
@users = User.where(:created_on => {:$gte => initial_date, :$lte => Time.now.utc})
@users.each do |user|
  puts user.name
end

Ruby Mongo驱动程序

initial_date = Time.utc(2011, 5, 1) # 2011-05-01 00:00:00 UTC
@conn = Mongo::Connection.new
@db = @conn['my_db']
@collection = @db['users']
@users = @collection.find(:created_on => {:$gte => initial_date, :$lte => Time.now.utc})
@users.each do |user|
  puts user['name']
end