Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

See existing indexes in MongoDB using mongoid

I'd like to see the existing indexes used by MongoDB. Can I do the equivalent of

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

using Mongoid?

$ rails console
> ?

Would be convenient from my heroku apps using MongoHQ. Thanks!

like image 738
oma Avatar asked Aug 30 '12 09:08

oma


People also ask

How do I view indexes in MongoDB?

You can find all the available indexes in a MongoDB collection by using the getIndexes method. This will return all the indexes in a specific collection. Result: The output contains the default _id index and the user-created index student name index.

How do I edit an existing index in MongoDB?

To modify an existing index in the MongoDB Shell, you need to drop and recreate the index. The exception to this rule is TTL indexes, which can be modified via the collMod command in conjunction with the index collection flag.

Where are indexes stored in MongoDB?

The index data is stored along with the collection data in the data directory of the MongoDB Server installation. You can also specify the data directory using the --dbpath storage option when you start the mongod.

Does MongoDB $in use index?

Generally, MongoDB only uses one index to fulfill most queries. However, each clause of an $or query may use a different index, and in addition, MongoDB can use an intersection of multiple indexes.


2 Answers

You can get at the underlying indexes for a Mongoid model through its collection.

> YourModel.collection.indexes

This reaches down into the moped driver (in Mongoid 3). See http://mongoid.org/en/moped/docs/driver.html

like image 186
Steve Avatar answered Sep 22 '22 00:09

Steve


To put Steve's answer to use, I added it to a module to do "common things":

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

That module can then be included in your class (useful during development):

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

Which can result in something like this in the console:

2.4.5 :031 > WaterSupply.show_indexes
 => [{"_id"=>1}, {"location"=>"2dsphere"}, {"address"=>1}, {"organization_id"=>1, "address"=>1}] 
like image 30
Jon Kern Avatar answered Sep 19 '22 00:09

Jon Kern