2

I am new to Mongo.

I am trying to query for a date range. The user model has this field:

  field     :confirmed_at,          :type => Time

could someone help me write a query to get users who confirmed their account for some time range?

Here is the error and the query I am trying:

> db.users.where(:confirmed_at.gte => Time.now, :confirmed_at.lte => 10.minutes.ago)
Tue May 29 17:45:37 SyntaxError: syntax error (shell):1
Model.where(:confirmed_at.gte => Time.now, :confirmed_at.lte => 10.minutes.ago)
Tue May 29 17:56:15 SyntaxError: syntax error (shell):1

Thanks!

GeekedOut
  • 16,905
  • 37
  • 107
  • 185

1 Answers1

9

I'm going to assume you are using mongoid by the way the field was declared.

You would want to use something like this:

Model.where(
  :confirmed_at.gte => Time.now,
  :confirmed_at.lte => 10.minutes.ago
)
Tyler Brock
  • 29,626
  • 15
  • 79
  • 79
  • thanks! yes I am using mongoid, but I am confused about how type is time and not date. Does that make a difference? – GeekedOut May 29 '12 at 21:35
  • I tried something like this db.users.where((:confirmed_at.gte => "1980-1-1", :confirmed_at.lte => "2000-1-1") ) but that gave a syntax error – GeekedOut May 29 '12 at 21:38
  • You have to parenthesis on the left side (near where). – Tyler Brock May 29 '12 at 21:39
  • this one also gives a syntax error :) db.users.where(:confirmed_at.gte => "1980-1-1", :confirmed_at.lte => "2000-1-1") – GeekedOut May 29 '12 at 21:40
  • Updated my example, try that instead. – Tyler Brock May 29 '12 at 21:42
  • same thing..syntax error :) I am switching Model. to db.users.where – GeekedOut May 29 '12 at 21:44
  • In the original question, please post the full model, the query, and the error. – Tyler Brock May 29 '12 at 21:48
  • You can't use db.collection in rails, that is shell syntax. Do it as I posted with the Model as the model name. In your case "Users". If you are trying to do this in the shell you will need to write the query a different way entirely. It would look like `db.users.find({created_at: {$gt: time1, $lt: time2}})` – Tyler Brock May 29 '12 at 21:52
  • I added what happenes after your suggestion..same thing :) Also added the model....thanks for your help!! – GeekedOut May 29 '12 at 21:56