107

Is there a way to see a list of indices on a collection in mongodb in shell? i read through http://www.mongodb.org/display/DOCS/Indexes but i dont see anything

Community
  • 1
  • 1
Timmy
  • 12,468
  • 20
  • 77
  • 107

7 Answers7

150

From the shell:

db.test.getIndexes()

For shell help you should try:

help;
db.help();
db.test.help();
mdirolf
  • 7,521
  • 2
  • 23
  • 15
38

If you want to list all indexes across collections:

db.getCollectionNames().forEach(function(collection) {
   indexes = db.getCollection(collection).getIndexes();
   print("Indexes for " + collection + ":");
   printjson(indexes);
});
Naman
  • 27,789
  • 26
  • 218
  • 353
Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226
13

And if you want to get list of all indexes in your database:

use "yourdbname"

db.system.indexes.find()
Marian Zagoruiko
  • 1,527
  • 3
  • 17
  • 29
11

Make sure you use your collection:

db.collection.getIndexes()

http://docs.mongodb.org/manual/administration/indexes/#information-about-indexes

Praveen
  • 55,303
  • 33
  • 133
  • 164
Kamilski81
  • 14,409
  • 33
  • 108
  • 161
6

You can also output all your indexes together with their size:

db.collectionName.stats().indexSizes

Also check that db.collectionName.stats() gives you a lot of interesting information like paddingFactor, size of the collection and number of elements inside of it.

Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
4

Taking this one step further, if you'd like to find all indexes on all collections, this script (modified from Juan Carlos Farah's script here) gives you some useful output, including a JSON printout of the index details:

 // Switch to admin database and get list of databases.
db = db.getSiblingDB("admin");
dbs = db.runCommand({ "listDatabases": 1}).databases;


// Iterate through each database and get its collections.
dbs.forEach(function(database) {
db = db.getSiblingDB(database.name);
cols = db.getCollectionNames();

// Iterate through each collection.
cols.forEach(function(col) {

    //Find all indexes for each collection
     indexes = db[col].getIndexes();

     indexes.forEach(function(idx) {
        print("Database:" + database.name + " | Collection:" +col+ " | Index:" + idx.name);
        printjson(indexes);
         });


    });

});
Community
  • 1
  • 1
DCaugs
  • 484
  • 5
  • 16
0

Using an old version of MongoDB here but one of the top answers in this question here did not work for me. This one worked:

db.getCollectionNames().forEach(function(collection) {
    print("Collection: '" + collection);
    print(db.getCollection(collection).getIndexes())
});
Julesezaar
  • 2,658
  • 1
  • 21
  • 21