Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoid date range query

I can't seem to find anything to make a date range query using Mongoid/Rails. Below are some queries I've tried (among about 100 others). If it returns anything, it always ignores the 'end_date'. Both dates are datetimes...

all(:conditions => {:created_at => start_date.to_datetime..end_date.to_datetime})

results in:

NoMethodError: undefined method `to_i' for Tue, 26 Apr 2011 00:00:00 +0000..Fri, 06 May 2011 00:00:00 +0000:Range

another example...

where(:created_at => {'$gte' => start_date,'$lt' => end_date})

results in a successful query but the end date is ignored. The results come back correctly after the start date but are not limited by the end date.

I've been working on this problem for several days to no avail. Not much help online, in the forums or IRC.

Would love to figure what I'm doing wrong :)

like image 787
Dustin Brewer Avatar asked May 06 '11 04:05

Dustin Brewer


People also ask

What is $date in MongoDB?

Date() returns the current date as a string in mongosh . new Date() returns the current date as a Date object. mongosh wraps the Date object with the ISODate helper. The ISODate is in UTC .

Does MongoDB have a date type?

The date field is the recommended data type to use when you want to store date and time information in MongoDB. It provides the flexibility to store date and time values in a consistent format that can easily be stored and retrieved by your application. Give the BSON Date data type a try for your applications.

What is ISO date in MongoDB?

ISODate("2012-12-19T06:01:17.171Z") ISODate() is a helper function that's built into to MongoDB and wraps the native JavaScript Date object. When you use the ISODate() constructor from the Mongo shell, it actually returns a JavaScript Date object.


1 Answers

There was a bug in Mongoid. Fixed now.

For more information:

https://github.com/mongoid/mongoid/issues/761

https://github.com/mongoid/mongoid/commit/f326de5acc969e1342e640dc026de7e94bf4cf49#lib/mongoid/matchers.rb

like image 181
Dustin Brewer Avatar answered Sep 24 '22 08:09

Dustin Brewer