19

我想看看 MongoDB 使用的现有索引。我可以做相当于

$ mongod
> use my_db
> db.system.indexes.find()

使用Mongoid?

$ rails console
> ?

从我使用 MongoHQ 的 heroku 应用程序会很方便。谢谢!

4

2 回答 2

30

您可以通过其获取 Mongoid 模型的基础索引collection

> YourModel.collection.indexes

这延伸到轻便摩托车司机(在 Mongoid 3 中)。见http://mongoid.org/en/moped/docs/driver.html

于 2012-08-30T12:44:25.793 回答
1

为了使用史蒂夫的答案,我将它添加到一个模块中来做“常见的事情”:

module CommonModelMethods
  extend ActiveSupport::Concern
  class_methods do
    def show_indexes
      self.collection.indexes.to_a.collect{|i| i[:key]}
    end
  end
end

然后可以将该模块包含在您的类中(在开发过程中很有用):

class WaterSupply
  include Mongoid::Document
  include CommonModelMethods
  ...
end

这可能会在控制台中产生类似的结果:

2.4.5 :031 > WaterSupply.show_indexes
 => [{"_id"=>1}, {"location"=>"2dsphere"}, {"address"=>1}, {"organization_id"=>1, "address"=>1}] 
于 2020-04-01T02:14:58.387 回答