MongoDB红宝石日期

时间:2010-04-17 16:36:03

标签: ruby-on-rails ruby mongodb mongoid

我有一个索引的集合:created_at(在这个特殊情况下应该是一个日期)

从rails中保存条目然后按日期检索它的正确方法是什么?

我正在尝试这样的事情:

型号: field:created_at,:type =>时间

脚本:

Col.create(:created_at => Time.parse(another_model.created_at).to_s

Col.find(:all,:conditions => {:created_at => Time.parse(同样的东西)})

并且它没有返回任何内容

2 个答案:

答案 0 :(得分:3)

Mongo驱动程序和各种ORM处理Date,Time和DateTime对象就好了;没有理由把它们变成字符串。

Col.create(:created_at => another_model.created_at)

找到:

Col.all(:created_at => another_model.created_at)

您不希望设置字符串,因为日期在内部存储为BSON Date对象,并且如此索引和搜索。如果将它们保存为字符串,则无法有效地执行大于/小于/范围比较的操作。

答案 1 :(得分:1)

Col.create(:created_at => Time.parse(another_model.created_at).to_s)

该行将您的时间对象作为String传递,取消to_s将其作为Time对象发送到ORM(MongoMapper或Mongoid)中的类型解析层。这是我能看到的唯一一个会导致它无效的错误。

相关问题