Question: How do you kill a slow query in MongoDB?


In MongoDB, dealing with long-running queries is crucial for maintaining optimal database performance. Here’s how to identify and kill a slow query.

Identifying Slow Queries

Before killing a slow query, you must first identify it. The currentOp() method is useful for this purpose. It shows currently executing operations in the MongoDB instance that are taking longer than a specified duration (in milliseconds).

db.currentOp({ "active": true, "secs_running": { "$gt": <thresholdInSeconds> } })

Replace <thresholdInSeconds> with the threshold duration in seconds. For example, to find queries running longer than 60 seconds, use "secs_running": {"$gt": 60}.

Killing a Slow Query

Once you've identified the slow query's opid from the output of currentOp(), you can kill it using the killOp command.


Replace <opid> with the operation ID of the slow query you wish to kill.


  1. Identify slow queries: First, find queries taking more than 60 seconds.

    var slowQueries = db.currentOp({ "active": true, "secs_running": { "$gt": 60 } });
  2. Kill the slow query: Assuming you found a slow query with an opid of 12345, you would kill it like so:


Important Considerations

  • Use this approach cautiously; abruptly terminating queries can affect ongoing operations or transactions.
  • Regularly monitor your MongoDB's performance to understand why slow queries occur, addressing underlying issues rather than frequently killing operations.

By following these steps, administrators and developers can manage and mitigate the impact of slow queries on their MongoDB instances.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.