Ruby 如何为模型获取新的mongoid索引
假设我用几个索引定义了我的模型人:Ruby 如何为模型获取新的mongoid索引,ruby,mongodb,mongoid,Ruby,Mongodb,Mongoid,假设我用几个索引定义了我的模型人: class Person include Mongoid::Document field :email field :ssn index({ email: 1 }, { unique: true }) index({ ssn: 1 }, { unique: true }) end 但是,只有电子邮件索引已经存在于数据库中,所以当我调用 Person.collection.indexes.each {|i| puts i.inspect}
class Person
include Mongoid::Document
field :email
field :ssn
index({ email: 1 }, { unique: true })
index({ ssn: 1 }, { unique: true })
end
但是,只有电子邮件索引已经存在于数据库中,所以当我调用
Person.collection.indexes.each {|i| puts i.inspect}
我得到以下回应:
{"v"=>1, "key"=>{"_id"=>1}, "name"=>"_id_", "ns"=>"x.person"}
{"v"=>1, "unique"=>true, "key"=>{"email"=>1}, "name"=>"email_1", "ns"=>"x.person"}
问题是,即使mongo中尚未创建已定义索引,我如何获得模型中已定义索引的列表
在我的情况下,此类列表应包括“ssn”字段的定义
换句话说……如何获取尚未创建的索引?刚刚找到它
我们可以将所有索引定义的列表放入模型中,如下所示:
Person.index_specifications
这是一个在加载应用程序时填充的数组,由“create_index”方法使用,如下所示:
显示在模型中定义的索引,无论其在数据库中是否存在
及
仅显示数据库中实际存在的索引
因此,还有一点值得注意:
rake db:mongoid:create_indexes
将在数据库中创建模型中定义的索引,并实际使用“index_specifications”方法
这会删除主键索引以外的所有索引:
rake db:mongoid:remove_indexes
因此,如果只想删除数据库中存在但不再在数据库中定义的索引,则应使用以下方法:
rake db:mongoid:remove_undefined_indexes
它们实际上使用了“未定义的索引”方法
我希望这能有所帮助
文件如下:
rake db:mongoid:remove_indexes
rake db:mongoid:remove_undefined_indexes