-
-
Save daniel-sc/431eefbdc47024a38c2f54927a0f886b to your computer and use it in GitHub Desktop.
Compact all collections inside of a MongoDB database
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
// This script loops though all collections of all db in a MongoDB and runs the compact operation on them | |
// Simply paste this into the Mongo shell | |
rs.secondaryOk(); | |
db.getMongo().getDBNames().forEach(function(dbName) { | |
if ("local" != dbName && "admin" != dbName && "system" != dbName /* use this to (re-)start: && dbName > "am"*/) { | |
var subject = db.getSiblingDB(dbName); | |
subject.getCollectionNames().forEach(function (collectionName) { | |
print(new Date() + ': Compacting: ' + dbName + " - " + collectionName); | |
sleep(1000); // assure a cancel (CTRL-C) after "done" is executed before compact command | |
var start = Date.now(); | |
subject.runCommand({ compact: collectionName }); | |
var duration = Date.now() - start; | |
print(new Date() + ': done, slepping sec ' + (duration/(5*1000))); | |
sleep(duration/5); // give some time to reduce replication lag | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi @rgaufman did you run it against the primary? maybe there was not much to do - see https://docs.mongodb.com/manual/reference/command/compact/#disk-space