Ruby Mongo Driver: How To Look For Date Intervals?

孤街浪徒 提交于 2020-03-05 03:09:52

问题


Given a init date and today, what's the query to search for all "names" between that date?

Thank you


回答1:


MongoMapper

You should be able to use MongoMapper's query operators. Suppose your have a "User" model with a "created_on" date, you could use this to get the names. (I believe MongoDB uses UTC Times to store all date/time objects):

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 Driver

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


来源:https://stackoverflow.com/questions/5969625/ruby-mongo-driver-how-to-look-for-date-intervals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!