Cacomania: Kill all long running MongoDB queries at once

Cacomania

Kill all long running MongoDB queries at once

Guido Krömer - 26. August 2014 - Tags: ,

If of some very running queries killing your MongoDB server you should try to execute the following piece of code in the shell. It kills all long running queries at once. You can define the maximum execution time by using the first parameter, which is set to 120 seconds by default.

(function (sec) {db.currentOp()['inprog'].forEach(function (query) { 
    if (query.op !== 'query') { return; } 
    if (query.secs_running < sec) { return; }  

    print(['Killing query:', query.opid, 
           'which was running:', query.secs_running, 'sec.'].join(' '));
    db.killOp(query.opid);
})})(120 /*The maximum execution time!*/);

This is the output generated by my little emergency helper:

Killing query: 598841625  which was running: 1892 sec.
Killing query: 598818776 which was running: 1931 sec.
Killing query: 598771338 which was running: 2048 sec.
Killing query: 577527534 which was running: 73569 sec.
Killing query: 577589300 which was running: 73404 sec.
Killing query: 577540188 which was running: 73535 sec.
Killing query: 598254342 which was running: 3114 sec.
Killing query: 597396058 which was running: 4811 sec.
Killing query: 597609629 which was running: 4382 sec.
Killing query: 597403975 which was running: 4801 sec.
Killing query: 597423364 which was running: 4766 sec.
Killing query: 597389768 which was running: 4842 sec.

I hope my little posting helped you, please let me know if you liked or disliked it.