Last active
August 20, 2024 12:18
-
-
Save 058c37a272bed3464d47f0b01038a16a/9a63286e7c034a2ff8da68631ccd0898 to your computer and use it in GitHub Desktop.
MongoDB script to print the document count, storage size and index size for all collections in all databases.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Created by RainoBoy97 | |
# https://gist.github.com/RainoBoy97/9a63286e7c034a2ff8da68631ccd0898 | |
mongo --quiet --eval ' | |
db = db.getSiblingDB("admin"); | |
var dbs = db.adminCommand("listDatabases").databases; | |
var totalCount = 0; | |
var totalStorageSize = 0; | |
var totalIndexSize = 0; | |
print("Database\tCollection\tCount\tStorage Size\tIndex Size"); | |
dbs.forEach(function(database) { | |
db = db.getSiblingDB(database.name); | |
cols = db.getCollectionNames(); | |
cols.forEach(function(collection) { | |
count = db[collection].count(); | |
totalCount += count; | |
storageSize = db[collection].storageSize(); | |
totalStorageSize += storageSize; | |
indexSize = db[collection].totalIndexSize(); | |
totalIndexSize += indexSize; | |
print(db + "\t" + collection + "\t" + count + "\t" + formatBytes(storageSize) + "\t" + formatBytes(indexSize)); | |
}); | |
}); | |
print("TOTAL\t-\t" + totalCount + "\t" + formatBytes(totalStorageSize) + "\t" + formatBytes(totalIndexSize)); | |
function formatBytes(bytes,decimals) { | |
if(bytes == 0) return "0 Bytes"; | |
var k = 1000, | |
dm = decimals + 1 || 0, | |
sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"], | |
i = Math.floor(Math.log(bytes) / Math.log(k)); | |
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + sizes[i]; | |
}; | |
' | column -s $'\t' -t |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment