A list of indices in MongoDB?

2019-01-16 17:11发布

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

6条回答
贪生不怕死
2楼-- · 2019-01-16 17:54

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.

查看更多
ら.Afraid
3楼-- · 2019-01-16 17:56

If you want to list all indexes:

db.getCollectionNames().forEach(function(collection) {
   indexes = db[collection].getIndexes();
   print("Indexes for " + collection + ":");
   printjson(indexes);
});
查看更多
走好不送
4楼-- · 2019-01-16 17:57

From the shell:

db.test.getIndexes()

For shell help you should try:

help;
db.help();
db.test.help();
查看更多
疯言疯语
5楼-- · 2019-01-16 18:02

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);
         });


    });

});
查看更多
Melony?
6楼-- · 2019-01-16 18:05

Make sure you use your collection:

db.collection.getIndexes()

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

查看更多
等我变得足够好
7楼-- · 2019-01-16 18:07

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

use "yourdbname"

db.system.indexes.find()
查看更多
登录 后发表回答