Skip to content

Instantly share code, notes, and snippets.

@daniel-sc
Forked from BlakeGardner/compact.js
Last active May 17, 2023 08:03
Show Gist options
  • Save daniel-sc/431eefbdc47024a38c2f54927a0f886b to your computer and use it in GitHub Desktop.
Save daniel-sc/431eefbdc47024a38c2f54927a0f886b to your computer and use it in GitHub Desktop.
Compact 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.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
});
}
});
@rgaufman
Copy link

rgaufman commented Nov 8, 2021

I tried this on 4.0 with wiredTiger and it did absolutely nothing with each collection taking 0.5 secs. Any ideas?

@daniel-sc
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment