I need to create a shell script that finds and kills long running mongo queries more than a specified threshold e.g. 15sec I plan to use db.currentOp(); and db.killOp(); to find and kill queries but I do not have much experience with shell scripts. how do I do this?


1 Answer 1


Just putting this here since I was struggling with the same for a while:

Here is how you can do it in python3 Tested on mongo version 4.0 and pymongo version 3.11.4

import pymongo

client = pymongo.MongoClient("mongodb://mongodb0.example.com:27017")
admin_db = client.get_database("admin")

milliseconds_running = 10000

query = [
    {"$currentOp": {"allUsers": True, "idleSessions": True}},
        "$match": {
            "active": True,
            "microsecs_running": {
                "$gte": milliseconds_running * 1000
            "ns": {"$in": ["mydb.collection1", "mydb.collection2"]},
            "op": {"$in": ["query"]},

ops = admin_db.aggregate(query)

count = 0

for op in ops:

    admin_db.command({"killOp": 1, "op": op["opid"]})

    count += 1

logging.info("ops found: %d" % count)

I wrote a more robust and configurable script for it here It also has a Dockerfile file in case anyone wants to use this as a container. I am currently using it as a periodic cleanup job.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.