Python script to get long running mongoDB queries using PyMongo

I am trying to get long running queries (sec_running >= 5) from MongoDB using Python.

Though the command works fine from Mongo console, it throws error or not working as expected when executed using PyMongo. Can someone please guide me on this ?.

How can I execute the below code from Python ?.

db.currentOp({“secs_running”: {$gte: 5}})

I am able to execute “currentOp” using PyMongo, however not able filter for the “secs_running”.

Please help, Thanks in advance. !

Hi @SAN,

The db.currentOp() from mongo shell is a wrapper for an admin command currentOp.

Using PyMongo, you can issue database commands using Database.command method. For currentOp database admin command you could try the following:

client = pymongo.MongoClient() 
database = client.admin 
response = database.command("currentOp", {"secs_running": {"$gt": 5}})

Regards,
Wan.

1 Like

Thanks Wan !.
Let me try with this script as well.

Hi Wan,

The commands gets executed successfully.
However the filter doesn’t work as expected.
The result set has all the queries that are running irrespective of the “secs_running” value.

Basically it’s the output of “currentOp” as it is.
Filter {"$gt": 5} doesn’t really seems to be working here.

Thanks agian.