Skip to content

Instantly share code, notes, and snippets.

@kylemclaren
Forked from comerford/killLongRunningOps.js
Last active September 24, 2024 12:05
Show Gist options
  • Save kylemclaren/3c09a4dda5991cf0bf9c to your computer and use it in GitHub Desktop.
Save kylemclaren/3c09a4dda5991cf0bf9c to your computer and use it in GitHub Desktop.
Find and (safely) kill long running MongoDB ops
db.currentOp().inprog.forEach(
function(op) {
if(op.secs_running > 5) printjson(op);
}
)
// kills long running ops in MongoDB (taking seconds as an arg to define "long")
// attempts to be a bit safer than killing all by excluding replication related operations
// and only targeting queries as opposed to commands etc.
killLongRunningOps = function(maxSecsRunning) {
currOp = db.currentOp();
for (oper in currOp.inprog) {
op = currOp.inprog[oper-0];
if (op.secs_running > maxSecsRunning && op.op == "query" && !op.ns.startsWith("local")) {
print("Killing opId: " + op.opid
+ " running for over secs: "
+ op.secs_running);
db.killOp(op.opid);
}
}
};
//example: killLongRunningOps(5)
@paravz
Copy link

paravz commented Oct 7, 2020

Thanks for this, i ended up using a modified version:

db.currentOp().inprog.forEach(                                                                                         
  function(op) {                                                                                                       
      if(op.secs_running > 5 )                                                                                        
                  print("host: " + op.host                                                                             
                    + " secs_running: " + op.secs_running                                                              
                    + " op: " + op.op                                                                                  
                    + " ns: " + op.ns                                                                                  
                    + " command: " + JSON.stringify(op.command)                                                        
                 );                                                                                                    
  }                                                                                                                    
);

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