32

how to get the list of all the databases in a mongo instance to a variable using pymongo?

for example to send following command to mongo instance using pymongo,

db.adminCommand( { listDatabases: 1 } )

2 Answers 2

50

Use database_names

dbs = MongoClient().database_names()

As Andrew Allaire points out: Starting in pymongo 3.6 database_names() has been deprecated in favour of list_database_names.

dbs = MongoClient().list_database_names()
Sign up to request clarification or add additional context in comments.

4 Comments

thank you :) can you please share if we have any good online resources working with pymongo?
The tutorials and examples on the official site are great
NOTE: Starting in pymongo 3.6 database_names() has been deprecated in favor of list_database_names(). api.mongodb.com/python/3.6.0/changelog.html
what about pymongo 3.4?
0

Since pymongo 3.6.0, there are two methods that return database names and depending on the use case either could be useful.

  • list_database_names: returns the list of the names of the databases on the server. For example:
    client = MongoClient(mongo_uri)
    
    client.list_database_names()
    # ['admin', 'data', 'scratch']
    
  • list_databases: returns a cursor over the databases which can be iterated over to get a list of dictionaries with basic metadata about the databases. For example:
    list(client.list_databases())
    
    # [{'name': 'admin', 'sizeOnDisk': 98304, 'empty': False},
    #  {'name': 'data', 'sizeOnDisk': 356352, 'empty': False},
    #  {'name': 'scratch', 'sizeOnDisk': 339968, 'empty': False}]
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.