-
-
Save blzzua/2bc2df8d054eb0cb54874e002ba2abce to your computer and use it in GitHub Desktop.
Compact/reorg/defragment 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.slaveOk(); for early versions | |
db.getMongo().getDBNames().forEach(function(dbName) { | |
if ("local" != dbName && "admin" != dbName && "system" != dbName && "config" != 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