mongodbcompact-database

Mongo DB Collection Compact


I have been looking at a way to reduce the size of a set of mongo databases that keep on growing in size. I am new to mongodb. I have looked at various methods for doing this and thought the following code might be the simplest way of achieving this without writing code for the specific databases:

db = db.getSiblingDB("admin"); 
dbs = db.runCommand({ "listDatabases": 1 }).databases; 

// Iterate through each database and get its collections. 
dbs.forEach(function(database) { 
    db = db.getSiblingDB(database.name); 
    db.getCollectionNames().forEach(function (collectionName) { 
        print('Compacting: ' + collectionName); 
        db.runCommand({ compact: collectionName }); 
        db.runCommand({ repairDatabase: 1 } ); 
    }); 
}); 

However, this runs on all databases and so I wasn't sure if this could be potentially dangerous to run?


Solution

  • The documentation mentions that it's probably a good idea to have a backup when running compact, however outside of Operation Termination they do not specifically list a reason why.

    It also says that it will block the operations for the database while the command is running so it's probably not a good idea to do this outside of the scheduled maintenance hours.