Search code examples
pythonmongodbpymongodatabase

Listing users for certain DB with PyMongo


What I'm trying to acheive

I'm trying to fetch users for a certain database.

What I did so far

I was able to find function to list the databases or create users but none for listing the users, I thought about invoking an arbitrary command such as show users but I could find any way to do it.

Current code

#/usr/bin/python

from pymongo import MongoClient

client = MongoClient("localhost",27017)
db = client.this_mongo

Trial and error

I can see the DB names and print them but nothing further:

db_names = client.database_names()

#users = db.command("show users")
for document in db_names:
    print(document)
#cursor = db.add_user('TestUser','Test123',roles={'role':'read'})

If there was only a function that could fetch the users cursor so I can iterate over it it would be great.

EDIT

Working solution

#/usr/bin/python

from pymongo import MongoClient

client = MongoClient("localhost",27017)
db = client.this_mongo

# This is the line I added with the help of @salmanwahed
listing = db.command('usersInfo')

for document in listing['users']:
    print document['user'] +" "+ document['roles'][0]['role']

Thank you all and @salmanwahed specifically!


Solution

  • You can execute the usersInfo command to fetch the users data. Like:

    db.command('usersInfo')
    

    It will return you a result like this: (I had created the testingdb for testing)

    {u'ok': 1.0,
     u'users': [{u'_id': u'testingdb.TestUser',
       u'db': u'testingdb',
       u'roles': [{u'db': u'testingdb', u'role': u'read'}],
       u'user': u'TestUser'}]}