Skip to content

Instantly share code, notes, and snippets.

@blzzua
Forked from daniel-sc/compact.js
Last active May 17, 2023 08:05
Show Gist options
  • Save blzzua/2bc2df8d054eb0cb54874e002ba2abce to your computer and use it in GitHub Desktop.
Save blzzua/2bc2df8d054eb0cb54874e002ba2abce to your computer and use it in GitHub Desktop.
Compact/reorg/defragment all collections inside of a MongoDB database
// 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