List Database Names - PyMongo - Examples


PyMongo List Database Names

To list databases present in a MongoDB instance,

  1. Create a client to the MongoDB instance.
  2. Using the client, call the list_databases() function.
  3. The function returns an iterator. Use a For loop to iterate through the list of databases.

Examples

1. List Databases Present in MongoDB Instance

In the following program, we connect to the MongoDB instance running locally. We then call list_databases() on the connection object, and using a For loop, print the database details.

Python Program

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

for db in myclient.list_databases():
    print(db)

Explanation:

  1. We import the pymongo library, which is used to interact with MongoDB in Python.
  2. We create a client object myclient to connect to the MongoDB instance running on localhost at port 27017.
  3. We call the list_databases() method on the myclient object to retrieve a list of all databases present in the MongoDB instance.
  4. Using a For loop, we iterate through each database and print its details.

Output


2. List Databases with Additional Information

In this example, we will list the databases and display additional information like the size of the database. This can be useful when you need more details about each database.

Python Program

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

for db in myclient.list_databases():
    print(f"Database Name: {db['name']} - Size: {db['sizeOnDisk']} bytes")

Explanation:

  1. We use the same MongoDB client connection.
  2. For each database, we access the name and size of the database by using the dictionary keys 'name' and 'sizeOnDisk'.
  3. We print the database name along with its size on disk in bytes.

Output


3. List Databases with a Filter (Database Type)

MongoDB does not provide a built-in method to filter databases based on types or conditions. However, you can manually filter the databases using Python's built-in functionalities.

In this example, we will list only databases whose names contain the word 'test'.

Python Program

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

for db in myclient.list_databases():
    if 'test' in db['name']:
        print(db['name'])

Explanation:

  1. After connecting to MongoDB, we use a for loop to iterate through the list of databases.
  2. We check if the word 'test' is in the name of each database using a simple conditional if 'test' in db['name'].
  3. If the condition is true, we print the database name.

Output


Summary

In this PyMongo Tutorial, we learned how to get the list of databases present in a MongoDB instance using the list_databases() function, with examples. We also explored how to retrieve additional information about the databases and filter the list based on specific criteria.


Python Libraries