0
0
MongodbHow-ToBeginner · 3 min read

How to Kill Operation in MongoDB: Syntax and Examples

To kill a running operation in MongoDB, use the db.killOp(opid) command where opid is the operation ID. First, find the operation ID by running db.currentOp(), then pass it to killOp to stop the operation.
📐

Syntax

The killOp command stops a running operation by its operation ID.

  • opid: The unique identifier of the operation to kill, obtained from db.currentOp().
javascript
db.killOp(opid)
💻

Example

This example shows how to find a running operation and kill it using killOp.

javascript
const currentOps = db.currentOp();
// Find an operation to kill (example: a long-running query)
const opToKill = currentOps.inprog.find(op => op.active && op.op !== 'none');
if (opToKill) {
  print('Killing operation with opid:', opToKill.opid);
  db.killOp(opToKill.opid);
} else {
  print('No active operation found to kill.');
}
Output
Killing operation with opid: 1234567890
⚠️

Common Pitfalls

  • Trying to kill an operation without the correct opid will fail silently or do nothing.
  • Operations that finish quickly may not be found in db.currentOp() when you try to kill them.
  • You need appropriate privileges to run killOp; otherwise, the command will be denied.
javascript
/* Wrong way: Using an invalid opid */
db.killOp(9999999999); // No effect if opid does not exist

/* Right way: Get opid from currentOp and kill */
const ops = db.currentOp();
const validOp = ops.inprog.find(op => op.active);
if (validOp) {
  db.killOp(validOp.opid);
}
📊

Quick Reference

CommandDescription
db.currentOp()Lists all current operations running on the server
db.killOp(opid)Kills the operation with the specified operation ID
opidOperation ID obtained from currentOp to identify the operation

Key Takeaways

Use db.currentOp() to find the operation ID before killing an operation.
Pass the correct opid to db.killOp(opid) to stop the running operation.
You must have proper permissions to kill operations in MongoDB.
Operations may finish before you can kill them, so act quickly.
Invalid opid values will not affect any operations.