Mongoid query by date ranges

后端 未结 2 985
忘了有多久
忘了有多久 2020-12-10 00:13

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

相关标签:
2条回答
  • 2020-12-10 00:54

    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})
    
    0 讨论(0)
  • 2020-12-10 00:59

    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)
    
    0 讨论(0)
提交回复
热议问题