22 Jun 2019
Finding and (Safely) Killing Long-Running MongoDB Ops
Find long-running ops
db.currentOp().inprog.forEach(
function(op) {
if (op.secs_running > 5) printjson(op);
}
)
Kill long-running ops
This script terminates long-running operations in MongoDB, taking a seconds parameter to define what counts as “long-running.” It prioritizes safety by filtering out replication operations and focusing exclusively on queries rather than broader command types.
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)