有时候在monogid中删除文档

我正在使用mongoid的rails app。 这是模型(集合)之一:

class Document include Mongoid::Document include Mongoid::Timestamps include Mongoid::Paperclip field :time, type: Time field :radius, type: Float attr_accessible :time,:radius end 

时间字段包含应删除模型的实际时间。 我怎么能这样做,我有一个想法,我必须写一个脚本把它放在cron工作。 但我不想创建一个cron工作。 有没有其他方法可以自动化这个或我在轨道模型中的任何方法我可以定义或仅内置到rails中的东西。 我肯定错过了一些东西。

您可以通过使用TTL索引在没有cron的情况下实现此目的。

您需要做的就是在该字段上放置一个TTL索引:

 db.log.events.ensureIndex( { "time": 1 }, { expireAfterSeconds: 3600 } ) // this means that it will expire in 1 hour after the time in the field `time` 

您可以使用delayed_job gem: https : //github.com/collectiveidea/delayed_job

 document.delay(run_at: time).destroy 

在模型中添加此行以实现它:

 index({:time => 1}, {background: true, expire_after_seconds: 0}) 

如果您的集合很大,也在后台执行索引。 您需要一个索引,因为要查找要删除的项目,您不希望必须遍历整个集合。