Skip to content

Instantly share code, notes, and snippets.

@iolufemi
Created June 13, 2024 07:59
Show Gist options
  • Save iolufemi/d45e56f04ed66409a405931c38fbc187 to your computer and use it in GitHub Desktop.
Save iolufemi/d45e56f04ed66409a405931c38fbc187 to your computer and use it in GitHub Desktop.
Recover disk space from mongodb
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);
print('OnDB: ' + database.name);
if(database.name == 'admin' || database.name == 'local'){
print('Skipping: ' + database.name);
}else{
db.getCollectionNames().forEach(function (collectionName) {
print('Compacting: ' + collectionName);
try{
db.runCommand({ compact: collectionName });
}catch(e){
print(e);
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment