database MongoDB 中的索引列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2789865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 07:43:11  来源:igfitidea点击:

A list of indices in MongoDB?

mongodbindexingdatabase-indexesmongodb-indexesdatabase

提问by Timmy

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/Indexesbut i dont see anything

有没有办法在shell中的mongodb中查看集合的索引列表?我通读了http://www.mongodb.org/display/DOCS/Indexes但我什么也没看到

回答by mdirolf

From the shell:

从外壳:

db.test.getIndexes()

For shell help you should try:

对于 shell 帮助,您应该尝试:

help;
db.help();
db.test.help();

回答by Somnath Muluk

If you want to list all indexes:

如果要列出所有索引:

db.getCollectionNames().forEach(function(collection) {
   indexes = db.getCollection(collection).getIndexes();
   print("Indexes for " + collection + ":");
   printjson(indexes);
});

回答by Marian Zagoruiko

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

如果您想获取数据库中所有索引的列表:

use "yourdbname"

db.system.indexes.find()

回答by Kamilski81

回答by Salvador Dali

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.

还要检查是否db.collectionName.stats()为您提供了许多有趣的信息,例如 paddingFactor、集合的大小和其中的元素数量。

回答by DCaugs

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:

更进一步,如果您想查找所有集合的所有索引,此脚本(从此处的Juan Carlos Farah 脚本修改)为您提供了一些有用的输出,包括索引详细信息的 JSON 打印输出:

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


    });

});