繁体   English   中英

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

[英]How do you get the size of an individual index in MongoDB?

我知道我可以使用db.collection.totalIndexSize()来获取总索引大小,但我对查看单个索引的大小很感兴趣。

这是支持的吗?

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

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

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

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

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

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

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

var reverse = true;
var sortField = "indexSizeInMB";

更改排序字段和顺序。

嘿 只需在 totalIndexSize() 函数中添加一个值作为

  • db.collection.totalIndexSize(1)

例如

db.test.totalIndexSize(1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM