Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Compact all collections inside of a MongoDB database
// This script loops though the list of collection names in a MongoDB and runs the compact operation on them
// Simply paste this into the Mongo shell
use testDbName;
db.getCollectionNames().forEach(function (collectionName) {
print('Compacting: ' + collectionName);
db.runCommand({ compact: collectionName });
});
@damaddin

This comment has been minimized.

Copy link

@damaddin damaddin commented Sep 21, 2017

Thanks! This goes one step further and iterates all db's and collections:

db.getMongo().getDBNames().forEach(function(dbName) {
    if ("local" != dbName && "admin" != dbName && "system" != dbName) {
        var subject = db.getSiblingDB(dbName);
        subject.getCollectionNames().forEach(function (collectionName) {
            print('Compacting: ' +dbName + " - " + collectionName);
            subject.runCommand({ compact: collectionName });
        });
    }
});
@ST-DDT

This comment has been minimized.

Copy link

@ST-DDT ST-DDT commented Oct 4, 2018

If you want to execute the command on a secondary member of your replicaSet then you need to execute the following first:

rs.slaveOk();

https://docs.mongodb.com/manual/reference/method/rs.slaveOk/
That way you can avoid downtimes. Please note that the server won't be available for failover during that time.

@devology-rob

This comment has been minimized.

Copy link

@devology-rob devology-rob commented Jun 10, 2019

FYI if you were prepared to take your database offline, you can run a repair that performs a compaction on all collections. This article covers the two approaches and discusses a rolling update which works great on MLab hosted databases https://dzone.com/articles/managing-disk-space-mongodb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.