How to run MongoDB commands with pymongo?

Question:

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?

Asked By: Rugnar

||

Answers:

Every method in the Python driver follows PEP 0008 unless I am strongly mistaken

In Pymongo you need to use the .current_op() method to get information on operations currently running.

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

Of course if you want to list currently idle operations in the result set the positional or keyword argument include_all to True

infos = db.current_op(True) # or infos = db.current_op(include_all=True)

Demo:

In [8]: db.current_op()
Out[8]: 
{'inprog': [{'active': True,
   'client': '127.0.0.1:54268',
   'connectionId': 2,
   'desc': 'conn2',
   'lockStats': {},
   'locks': {},
   'microsecs_running': 45,
   'ns': 'admin.$cmd',
   'numYields': 0,
   'op': 'command',
   'opid': 793,
   'query': {'$all': False, 'currentOp': 1},
   'secs_running': 0,
   'threadId': '140272266217216',
   'waitingForLock': False}],
 'ok': 1.0}

To issue a MongoDB command, the driver provides the .command() method

Answered By: styvane

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)
Answered By: disflux

Just for reference, this no longer works in current versions of PyMongo (4.0 or more recent).

The following example is from the documentation:

# Lists all operations currently running on the server.
with client.admin.aggregate([{"$currentOp": {}}]) as cursor:
    for operation in cursor:
        print(operation)

See https://pymongo.readthedocs.io/en/stable/api/pymongo/database.html#module-pymongo.database

As to why it was changed from the more straightforward method call is left as an exercise for the student.

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.