Mongoid query by date ranges

2019-01-18 08:44发布

问题:

How i can write where query by two date ranges? The only condition is that this data must be retrieved by one query. Thank you.

UPD: or how to union 2 queries in one collection? not array

回答1:

You can easily or the two ranges:

Post.all.
     or(:created_at.gt => Time.now - 3.months, :created_at.lte => Time.now - 2.months).
     or(:created_at.gt => Time.now - 1.month, :created_at.lte => Time.now)


回答2:

Union could be done using any_of criteria. any_of criteria is similar to SQL OR and is aliased as "or" for readability.Here is how to query for two time ranges.

date1 = Date.new(2016,2,3)
date2 = Date.new(2016,2,4)
date3 = Date.new(2016,3,3)
date4 = Date.new(2016,3,4)
User.any_of({:created_at=>  date1..date2},{:created => date3..date4})