Rails根据日期范围限制结果

时间:2013-12-16 10:28:54

标签: ruby-on-rails ruby-on-rails-4 mongoid

我在数据库中有以下Strucuture

db.slots.find().pretty()
{
    "_id" : ObjectId("52ae8990bd521b2da7000003"),
    "created_at" : ISODate("2013-12-16T05:03:12.345Z"),
    "day_from" : "Mon",
    "day_to" : "Sat",
    "doctor_clinic_id" : ObjectId("52ae8990bd521b2da7000004"),
    "evening_time_from" : 0,
    "evening_time_from_period" : "AM",
    "evening_time_to" : 0,
    "evening_time_to_period" : "AM",
    "morning_time_from" : 9,
    "morning_time_from_period" : "AM",
    "morning_time_to" : 2,
    "morning_time_to_period" : "PM",
    "store" : [
        ISODate("2013-12-13T09:00:00Z"),
        ISODate("2013-12-13T09:15:00Z"),
        ISODate("2013-12-13T09:30:00Z"),
        ISODate("2013-12-13T09:45:00Z"),
        ISODate("2013-12-13T10:00:00Z"),
        ISODate("2013-12-13T10:15:00Z"),
        ISODate("2013-12-13T10:30:00Z"),
        ISODate("2013-12-13T10:45:00Z"),
        ISODate("2013-12-13T11:00:00Z"),
        ISODate("2013-12-13T11:15:00Z"),
        ISODate("2013-12-13T11:30:00Z"),
        ISODate("2013-12-13T11:45:00Z"),
        ISODate("2013-12-13T12:00:00Z"),
        ISODate("2013-12-13T12:15:00Z"),
        ISODate("2013-12-13T12:30:00Z"),
        ISODate("2013-12-13T12:45:00Z"),
        ISODate("2013-12-13T13:00:00Z"),
        ISODate("2013-12-13T13:15:00Z"),
        ISODate("2013-12-13T13:30:00Z"),
        ISODate("2013-12-13T13:45:00Z"),
........
.....
..
        ISODate("2013-12-25T13:15:00Z"),
        ISODate("2013-12-25T13:30:00Z"),
        ISODate("2013-12-25T13:45:00Z"),
        ISODate("2013-12-25T14:00:00Z")
    ],
    "updated_at" : ISODate("2013-12-16T05:03:12.345Z")
}

我想只获取商店的内容,该商店的日期为今天和接下来的五天。

当我尝试以下操作时,我会收到一个插槽

slots.where(:store.gte => Date.today)

结果

#<Mongoid::Criteria selector: {"doctor_clinic_id"=>"52ae8990bd521b2da7000004", "store"=>{"$gte"=>Mon, 16 Dec 2013}} options: {} class: Slot embedded: false> 

slot.rb

class Slot
  include Mongoid::Document
field :store, type: Array

  belongs_to :clinic
end

slot.store.where(:store.gte => Date.today)产生如上所述的输出.. !!!

1 个答案:

答案 0 :(得分:1)

首先:你想要实现的是MongoDB中的投影,当你只想从元素中检索某些字段时使用它。实际上,您要做的是从数组字段中检索某些元素(请参阅Mongodb projection positional

在mongo你尝试这样的事情:

query={}
projection = {day_from:1, day_to:1} //Retrieve only _id, day_from and day_to fields
db.slots.find(query,projection).pretty()

Mongodb projection positional是您需要的,但文档说它只返回与查询匹配的第一个元素。

所以我猜你不能直接用mongo。我建议你尝试不同的方法,如格式化程序和虚拟属性。类似于:

class Slot
  include Mongoid::Document
  field :store, type: Array

  def with_dates_after date
    self.virtual_store= self.store.select{|elem| elem >= date} 
  end

  def virtual_store= arg_arr
    @_virtual_store = arg_arr
  end

  def virtual_store
   @_virtual_store ||= []
  end

end