Querying last 30 days date range with Mongoid and Ruby? Querying last 30 days date range with Mongoid and Ruby? mongodb mongodb

Querying last 30 days date range with Mongoid and Ruby?


There's a simpler way:

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

Adjust time range to suit.


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")] += 1end

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 agostart_day       = 10end_day         = 20Sale.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.


You can also write the query by using the between method like:

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