Last active
April 19, 2024 15:13
-
-
Save shadyrudy/6e94661d453e7882f8a1877517f40c04 to your computer and use it in GitHub Desktop.
MongoDB - Get collections, collection count, and size in MB
This file contains 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
// Get the current timestamp in ISO 8601 format and adjust it to the desired format | |
var timestamp = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, ''); | |
// Print the header line for the CSV, including database name and timestamp | |
print("databaseName,timestamp,collectionName,documentCount,collectionSizeMB"); | |
// Get the name of the current database | |
var dbName = db.getName(); | |
// Get the list of all collection names in the current database | |
var collections = db.getCollectionNames(); | |
// Iterate over each collection | |
collections.forEach(function(collectionName) { | |
// Get the number of documents in the collection | |
var count = db[collectionName].count(); | |
// Get the collection statistics | |
var stats = db[collectionName].stats(); | |
var sizeInBytes = stats.size; | |
var sizeInMB = sizeInBytes / 1024 / 1024; | |
// Print the database name, timestamp, collection name, document count, and size in MB in CSV format | |
print(dbName + "," + timestamp + "," + collectionName + "," + count + "," + sizeInMB); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment