S.D.
S.D.

Reputation: 1201

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

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 } )

Upvotes: 32

Views: 31635

Answers (2)

cottontail
cottontail

Reputation: 23111

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}]
    

Upvotes: 0

Steve Rossiter
Steve Rossiter

Reputation: 2925

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()

Upvotes: 48

Related Questions