Skip to content

Instantly share code, notes, and snippets.

@BlakeGardner
Last active October 10, 2024 11:19
Show Gist options
  • Save BlakeGardner/8548102 to your computer and use it in GitHub Desktop.
Save BlakeGardner/8548102 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link

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.

@RobbiewOnline
Copy link

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

@spotlesscoder
Copy link

@ST-DDT which server versions do these constraints apply to? (I mean that the secondary node won't be avail for failover?)

Can you please point me to the according documentation? Thanks :)

@blzzua
Copy link

blzzua commented May 8, 2023

rs.slaveOk();

for actual versions must be:
rs.secondaryOK();

anyway thanks.

@ConorSheehan1
Copy link

ConorSheehan1 commented Feb 19, 2024

db.getCollectionNames returns views too 🙃

Returns an array containing the names of all collections and views

https://www.mongodb.com/docs/manual/reference/method/db.getCollectionNames/

If you want collection names only you need something like db.getCollectionInfos({ type: 'collection' }).map(v => v.name).filter(v => v != 'system.views')

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