你如何获得MongoDB中单个索引的大小?

Zac*_*ach 34 mongodb

我知道我可以db.collection.totalIndexSize()用来获得总索引大小,但我有兴趣看到单个索引的大小.

这支持吗?

Rem*_*iet 47

当然可以.db.collection.stats().indexSizes是一个嵌入式文档,其中每个索引名称都是一个键,值是以字节为单位的总索引大小:

> db.test.stats()
{
        "ns" : "test.test",
         <snip>
        "indexSizes" : {
                "_id_" : 137904592,
                "a_1" : 106925728
        },
        "ok" : 1
}
Run Code Online (Sandbox Code Playgroud)


Nic*_*ico 8

这是一个简单的脚本,可以找出占用整个数据库中最多空间的索引:

var indexesArr = {}
db.getCollectionNames().forEach(function(collection) {
   indexes = db[collection].stats().indexSizes
   for (i in indexes) indexesArr[collection + " - " + i] = indexes[i];
});

var sortable = [], x;
for (x in indexesArr) sortable.push([x, indexesArr[x]])
var pArr = sortable.sort(function(a, b) {return b[1] - a[1]})
for (x in pArr) print( pArr[x][1] + ": " + pArr[x][0] );
Run Code Online (Sandbox Code Playgroud)


Sub*_*der 7

列出特定数据库中每个集合的索引大小,我们可以使用以下代码片段:

use mydb;

var collectionStats = []

// Get the sizes
db.getCollectionNames().forEach(function (collectionName) {
    var collection = db.getCollection(collectionName)
    var collectionIndexSize = collection.totalIndexSize();
    var indexSizeInMB = collectionIndexSize/(1024*1024)
    collectionStats.push({"collection": collectionName, "indexSizeInMB": indexSizeInMB})
});

// Sort on collection name or index size
var reverse = true;
var sortField = "indexSizeInMB";
collectionStats.sort(function (a, b) {
    comparison = a[sortField] - b[sortField];
    if (isNaN(comparison)) comparison = a.collection.localeCompare(b.collection);
    if (reverse) comparison *= -1;
    return comparison;
});undefined;

// Print the collection stats
collectionStats.forEach(function (collection) {
    print(JSON.stringify(collection));
});

// Total size of indexes
print("Total size of indexes: " + db.stats()["indexSize"]/(1024*1024) + " MB");
Run Code Online (Sandbox Code Playgroud)

您可以在上面的代码片段中更改变量的值

var reverse = true;
var sortField = "indexSizeInMB";
Run Code Online (Sandbox Code Playgroud)

更改排序字段和顺序。