Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying last 30 days date range with Mongoid and Ruby?

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?

like image 752
ghstcode Avatar asked Oct 15 '11 14:10

ghstcode


2 Answers

There's a simpler way:

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

Adjust time range to suit.

like image 165
tomblomfield Avatar answered Oct 22 '22 08:10

tomblomfield


Here's how to do it all in rubyland:

sales_by_date = Hash.new(0)

Sale.where(:created_at.gte => (Date.today - 30)).order_by(:created_at, :desc).each do |s|
  sales_by_date[s.created_at.strftime("%m-%d")] += 1
end

This will create a hash with "month-day" keys, reason is that some months have fewer than 30 days and will result in a key collision if the query is always 30.

If you want a different range, change the query:

# Between 10 and 20 days ago
start_day       = 10
end_day         = 20

Sale.where(:created_at.gte => (Date.today - end_day), :created_at.lte => (Date.today - start_day))

Change created_at to whatever the name of your datetime field is.

like image 26
Dan Healy Avatar answered Oct 22 '22 06:10

Dan Healy