Skip to content

Instantly share code, notes, and snippets.

@irasally
Created October 3, 2012 05:07
Show Gist options
  • Save irasally/3825128 to your computer and use it in GitHub Desktop.
Save irasally/3825128 to your computer and use it in GitHub Desktop.
[mongodb] run command 'compact' for all collections
#!/bin/sh
mongo localhost:27017/mongo run_command.js
mongo localhost:27018/mongo run_command.js
mongo localhost:27019/mongo run_command.js
# if you don't need connection infomation etc., use --quiet option.
# http://www.mongodb.org/display/DOCS/--quiet
var CompactCommand= function(){
var self = this;
this.start = new Date(); // measure running time
this.exec = function(){
printDbStats(); // before dbstats
execCommand();
printDbStats(); // after dbstats
}
this.calcExecTime = function(){
var end = new Date();
return end.getTime() - self.start.getTime();
}
function printDbStats(){
print('dbstats are');
printjson(db.runCommand('dbstats'));
}
function execCommand(){
db.getCollectionNames().forEach( function(name){
if(name != 'system.indexes'){
var commandStart = new Date(); // measure running time per collections
var result = db.runCommand({compact: name});
var commandEnd = new Date();
print( name + ' : ' + tojson(result) + ' [' + (commandEnd.getTime() - commandStart.getTime()) + ' mesc.]');
}
});
}
}
// see https://github.com/mongodb/mongo-snippets/blob/master/js/compact-example.js
var ReplSetHelper = function(){
this.stepDown = function(){
try {
print("step down.......");
rs.stepDown();
} catch(e) {
print("[Exception] " + e);
}
// reconnect
rs.isMaster();
while( 1 ) {
var m = rs.isMaster();
if( m.ismaster ) {
print("[ERROR] no one took over during our stepDown duration. we are primary again!");
assert(false);
}
if( m.primary ){
print("OK. Another node becomes primary!");
break;
}
print("waiting for another node to become primary....");
sleep(1000);
}
}
}
print('=== compact collections start. ===');
var command = new CompactCommand();
if(rs.isMaster().setName){
print("Replica Set:");
if( rs.isMaster().ismaster ){
print("This node is primary, so need to be secondary.");
new ReplSetHelper().stepDown();
}
rs.slaveOk(); // To be able to read for getting all collections name, in this session.
} else {
print("Single Node:");
}
command.exec();
print('=== compact collections done. [' + command.calcExecTime() + ' mesc.] ===');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment