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!
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.
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.
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.
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.
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
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}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With