donald
donald

Reputation: 23747

Ruby Mongo Driver: How To Look For Date Intervals?

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

Thank you

Upvotes: 0

Views: 5045

Answers (1)

Dylan Markow
Dylan Markow

Reputation: 124439

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

Upvotes: 9

Related Questions