MongoMapper: finding all documents created on a specified date
Asked Answered
T

4

6

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 } )
Thermography answered 21/11, 2011 at 23:10 Comment(1)
The link above doesn't work anymore.Schematize
T
5

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 } )
Thermography answered 12/1, 2012 at 15:0 Comment(0)
C
3

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.

Compressed answered 22/11, 2011 at 0:19 Comment(0)
O
2

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

Oregon answered 21/11, 2011 at 23:36 Comment(0)
P
0

Use the technique @mu-is-to-short pointed out to create the date.

But the format of the where statement can be simpler:

date = Time.new(2021,1,24, 0,0,0).utc
docs = Document.where(:updated_at.gte => date).all
Plumose answered 2/2, 2021 at 1:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.