Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoMapper: finding all documents created on a specified date

I need to write a query that finds all documents created on a specified date.

Let's suppose that the date is today.

I tried this:

Document.all(:created_at => Date.parse(Time.now.strftime('%Y/%m/%d')))

but I got:

Cannot serialize an object of class Date into BSON.

Thanks for your help.

UPDATE This link explains how to do so Date Range Queries With MongoMapper.

Document.count( :created_at => { '$gt' => 2.days.ago.midnight, '$lt' => 1.day.ago.midnight } )
like image 298
Laura Avatar asked Nov 21 '11 23:11

Laura


3 Answers

UPDATE: This link explains how to do so Date Range Queries With MongoMapper.

Document.count( :created_at => { '$gt' => 2.days.ago.midnight, '$lt' => 1.day.ago.midnight } )
like image 165
Laura Avatar answered Nov 17 '22 21:11

Laura


Your :created_at is a Date (as in "JavaScript-style Date with both date and time-of-day components"), right? You'll need to figure out the boundaries of the date in question in UTC, build Time instances for those boundaries, and then search for everything between those times.

Assuming that your local time zone is correctly configured and you want everything that was created on 2011-11-21, then something like this should get you there:

start_time = Time.new(2011,11,21, 0,0,0).utc
end_time   = Time.new(2011,11,22, 0,0,0).utc
docs       = Document.where(:created_at => { :$gte => start_time }).
                      where(:created_at => { :$lt  => end_time   })

You could also use Time.new(2011, 11, 21).utc and Time.new(2011, 11, 22).utc but I like the extra zeros as a reminder that I'm not really working with just a date.

like image 23
mu is too short Avatar answered Nov 17 '22 21:11

mu is too short


Just use Time.now instead. The ruby driver knows how to deal with Time objects.

doc = {:created_at => Time.now}

or

doc = {:created_at => Time.utc(12,1,12)} # year, month, day

Then, you can test if the document will serialize without throwing an error in irb like this:

require 'bson'

BSON.serialize(doc)

If you get an error, try again. If it spits out a serialized bson object, you are good to go!

If you are curious, check out the source of the to_mongo method in the mongomapper driver here

like image 32
Tyler Brock Avatar answered Nov 17 '22 19:11

Tyler Brock