Mongoid query by date ranges

2019-01-18 07:55发布

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

2条回答
闹够了就滚
2楼-- · 2019-01-18 08:42

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})
查看更多
Lonely孤独者°
3楼-- · 2019-01-18 08:43

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)
查看更多
登录 后发表回答