I know I can use db.collection.totalIndexSize()
to get the total index size, but I'm interested in seeing the size of an individual index.
Is this supported?
I know I can use db.collection.totalIndexSize()
to get the total index size, but I'm interested in seeing the size of an individual index.
Is this supported?
Certainly can. db.collection.stats().indexSizes
is an embedded document where each index name is a key and the value is the total index size in bytes :
> db.test.stats()
{
"ns" : "test.test",
<snip>
"indexSizes" : {
"_id_" : 137904592,
"a_1" : 106925728
},
"ok" : 1
}
This is an easy script to find out the indexes that take up the most space in your entire database:
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] );
Listing down the size of indexes per collection in a specific db we can use the following code snippet:
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");
You can change the value of variables in the snippet above
var reverse = true;
var sortField = "indexSizeInMB";
to change the sorting field and order.
Hey Just add a value in the totalIndexSize() function as
for example
db.test.totalIndexSize(1)