Skip to content

Instantly share code, notes, and snippets.

@comerford
Last active February 3, 2022 17:51
Show Gist options
  • Star 43 You must be signed in to star a gist
  • Fork 23 You must be signed in to fork a gist
  • Save comerford/9248866 to your computer and use it in GitHub Desktop.
Save comerford/9248866 to your computer and use it in GitHub Desktop.
// 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);
}
}
};
Copy link

ghost commented Sep 5, 2017

hi, I have trouble implementing this in nodejs. I keep getting the error currentOp is not a function. Can you tell me what db is in your script? Is it the value returned from MongoClient.connect()? Also, are you using the mongodb driver?

@thapakazi
Copy link

thapakazi commented Nov 13, 2017

Many thanks @comerford
@sc4224 its a query used in raw mongo console.

I have it appended to my ~/.mongorc.js

@th3nate
Copy link

th3nate commented May 24, 2018

implementation using mongoose driver:

            let db = mongoose.connection.db;
            db.command({ currentOp: 1 }, function (err, result) {
                if (err) {
                    console.error(`Agenda :: Kill long mongo queries | Error: ${err}`);
                } else {
                    for (let oper in result.inprog) {
                        let op = result.inprog[oper - 0];
                        if (op.secs_running > ENUMS.MONGO_KILL_AFTER_SECONDS && op.op === "query" && !op.ns.startsWith("local")) {
                            console.info(`Agenda :: Kill long mongo queries | Killing opId: ${op.opid} Running over ${op.secs_running}`);
                            db.killOp(op.opid);
                        }
                    }
                }
            });

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