Querying last 30 days date range with Mongoid and Ruby?

SeanNieuwoudt picture SeanNieuwoudt · Oct 15, 2011 · Viewed 23.9k times · Source

How do I go about querying a date range (of say the last 30 days from now) with Mongoid and Ruby?

I need to end up with an array or hash like the following:

{
    15 => 300,
    14 => 23,
    13 => 23
    ...
    30 => 20  # Goes over into previous month
    28 => 2
}

I am currently storing each document with a DateTime instance as well as a unix timestamp Integer field.

The keys in the above hash are the days and the values are the sum of all sales for those days.

Any ideas?

Answer

tomblomfield picture tomblomfield · Jun 16, 2012

There's a simpler way:

Sale.where(created_at: (30.days.ago..Time.now))

Adjust time range to suit.