ruby - 如何为模型获取新的 mongoid 索引

标签 ruby mongodb mongoid

假设我用几个索引定义了我的模型 Person:

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 

显示模型中定义的索引,无论它是否存在于数据库中。

Person.collection.indexes

只显示数据库中实际存在的索引。

所以还有一点值得关注:

rake db:mongoid:create_indexes 

将在数据库中创建模型中定义的索引,它实际上使用了方法'index_specifications'。

虽然这会删除除主键索引之外的所有索引:

rake db:mongoid:remove_indexes 

所以当你只想删除数据库中存在但不再定义在数据库中的索引时,你应该使用这个:

rake db:mongoid:remove_undefined_indexes

在契约中使用方法“undefined_indexes”。

希望对您有所帮助。

文档在这里:

https://mongoid.github.io/en/mongoid/docs/indexing.html

http://www.rubydoc.info/github/mongoid/mongoid/Mongoid/Tasks/Database#create_indexes-instance_method

关于ruby - 如何为模型获取新的 mongoid 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35613197/

相关文章:

ruby - 数组初始化和方法计数增加 ?秘诀是什么?

mongodb - .explain() 中额外的 "nscanned"是从哪里来的?

php - 如何在 Waterline 或 MongoDB 中选择、分组和加入

ruby-on-rails - MongoDB/Mongoid : Can one query for ObjectID in embedded documents?

ruby - MongoDB + ruby 。如何访问文档属性?

ruby - 如何在 Ruby 中复制散列?

ruby-on-rails - 对象的属性

ruby-on-rails - 从 Rails 应用程序的角度来看,group 和 group_by 的 mongoid 版本是什么?

ruby - "Display information for each person"

mongodb - 如何使用配置文件通过/etc/init.d/mongodb 启动 mongodb?