I wanted to execute raw mongo commands like (db.getUsers()) through the pymongo SDK. For example I have some js file which will contain only db.getUsers() in it . My python program needs to execute that command through establishing connection . I tried this db.command , db.runCommand but I'm not able to achieve that. After establishing the connection it should execute the mongo command whatever in the js file. Please assist.
1 Answer
db.getUsers() is a shell helper script to the usersInfo command (see https://docs.mongodb.com/manual/reference/method/db.getUsers/)
db.getUsers() wraps the usersInfo: 1 command.
You can run the usersInfo command using db.command() in pymongo with something like
from pymongo import MongoClient
db = MongoClient()['admin']
command_result = db.command({'usersInfo': 1})
print(command_result)
4 Comments
Belly Buster
That's only half the stack trace so can't really tell what's up.
Abyy
Its working Belly thank you
Abyy
So for all the python commands do we need to convert them into these Pymongo commands ? is there anyway I ca execute directly db.getUsers() directly , or something like show dbs directly from PyMongo sdk?
Belly Buster
So you have to understand that when you are running db,getUsers and various other "admin" commands, these are just mongo shell helper scripts that wrap the more complicated db.command function. Just because you can run them at the shell does not mean the exact commands can be run in the various language APIs such as pymongo. But you can run the db.command equivalent as outlined in the answer. Hope this makes sense.