Skip to content
Advertisement

How to run MongoDB commands with pymongo?

I need to see list of connections to MongodDB. I know how to do it in mongo console:

> db.currentOp(true)

Now I want to do the same using pymongo. I tried following and it didn’t work:

from pymongo import MongoClient
client = MongoClient(host="myhost.com")
db = client.mydb

After that I used db.command() in various combinations trying to pass "db.currentOp(true)" to it without success.

How to do it properly? The question is how to run a command using pymongo if I know how to run it from db console? Is there a common approach?

Advertisement

Answer

A quick glance over the API lead me to what I think you are looking for.

When I worked with PyMongo in the past, something I noticed is that the camelcase functions in the mongo shell (such as db.currentOp()), are converted directly to the python syntax, so it becomes db.current_op().

Try this:

from pymongo import MongoClient
client = MongoClient(host="myhost.com")
db = client.mydb
current_ops = db.current_op(True)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement