Sum of Sizes of All MongDB Databases

Can someone help to get sum of sizes of all Databases sizes. Just need to tune below query to get SUM of mdb.stats(102410241024).storageSize . Kindly Help in resolving this.

db.adminCommand("listDatabases").databases.forEach(function (d) {
   mdb = db.getSiblingDB(d.name);
   printjson(mdb.stats(1024*1024*1024).storageSize.sum);
})

Hello,

You could try to use just the below command.

db.adminCommand("listDatabases").totalSizeMb;

This should return the sum of all the sizeOnDisk fields, expressed in megabytes. as per this documentation link.

Regards,
Mohamed Elshafey

1 Like

Any possibility to get by using db.stats(). I need sum using that command. If you see , I am printing values. instead i need to sum all values.

Hi @Krishna_Sai1

How about replacing the print statement there with an addition operation?

let totalSize = 0
db.adminCommand("listDatabases").databases.forEach(function (d) {
    mdb = db.getSiblingDB(d.name);
    totalSize += mdb.stats(1024*1024*1024).storageSize
 })
print(`total size: ${totalSize}`)

or, slightly less readable:

db.adminCommand("listDatabases").databases.reduce(
  (b,a) => b + db.getSiblingDB(a.name).stats(1024*1024*1024).storageSize, 0
)

Would this work? Note that this is very untested, so make sure this code is correct before relying on it :slight_smile:

Best regards
Kevin

1 Like

Thanks for the script this is working fine. can we exclude the 3 databases(admin,local,config) using the same query .

db.adminCommand(“listDatabases”).databases.reduce(
(b,a) => b + db.getSiblingDB(a.name).stats(102410241024).storageSize, 0
)

can we exclude the 3 databases(admin,local,config) using the same query .

You can, although I think it may be better to use your original loop instead:

let totalSize = 0
db.adminCommand("listDatabases").databases.forEach(function (d) {
    mdb = db.getSiblingDB(d.name);
    if (!['admin', 'config', 'local'].includes(d.name)) {
        totalSize += mdb.stats(1024*1024*1024).storageSize
    }
 })
print(`total size: ${totalSize}`)

but you also might find this readable:

db.adminCommand("listDatabases").databases.
filter(
    n => !['admin', 'config', 'local'].includes(n.name)).
reduce(
    (b,a) => b + db.getSiblingDB(a.name).stats(1024*1024*1024).storageSize, 0)

However I believe this is mainly a Javascript question by now, as this method is not limited to MongoDB, but general Javascript operation on any array of objects.

I suggest if you’re having issues with Javascript coding, you might want to ask the relevant questions in a programming-oriented site such as StackOverflow.

Best regards
Kevin

1 Like

Thanks a lot Script is working as expected. :slight_smile: