PyMongo: How to List All Databases

Updated: February 6, 2024 By: Guest Contributor Post a comment

Overview

Working with MongoDB through Python becomes significantly more convenient with the use of PyMongo. PyMongo is a Python distribution containing tools for interacting with MongoDB, and one of the most common requirements for developers is the ability to list all databases in a MongoDB server. This tutorial will cover various ways – from basic to advanced – to list databases using PyMongo, including code examples and expected outputs.

Getting Started

Before diving into how to list databases, it’s important to ensure you have MongoDB and PyMongo installed. You can install PyMongo using pip:

pip install pymongo

Ensure MongoDB is running on your machine or connect to a remote MongoDB server. The connection to a MongoDB server is established through a MongoDB client.

from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')

This code snippet will connect you to the default localhost MongoDB server.

Basic Listing of Databases

The simplest way to list all databases is using the list_database_names() method:

db_list = client.list_database_names()
print(db_list)

This method returns a list of database names in the connected MongoDB server. The output will resemble something like:

['admin', 'local', 'test']

Note that MongoDB automatically creates the ‘admin’ and ‘local’ databases, so even on a new server, you won’t get an empty list.

Finding Specific Databases

While listing all databases is informative, in practice, you might be interested in checking if specific databases exist. You can achieve this by filtering the output from list_database_names():

specific_db = 'mydatabase'
if specific_db in client.list_database_names():
    print(f"Database {specific_db} exists.")
else:
    print(f"Database {specific_db} does not exist.")

This snippet will check for the presence of ‘mydatabase’ in the server.

Advanced Database Insights

PyMongo also allows for more detailed insights into each database, such as their size and document count, via the list_databases() method. This returns detailed information about each database:

for db_info in client.list_databases():
    print(f"Database name: {db_info['name']}, Size on Disk: {db_info['sizeOnDisk']}")

Thisadvanced technique provides a more comprehensive view of the databases, beyond just their names.

Using Database Filters

In some scenarios, you might only be interested in databases that meet certain criteria, like a minimum size. PyMongo allows you to filter databases in such cases:

for db_info in client.list_databases():
    if db_info['sizeOnDisk'] > 1024 * 1024: # Larger than 1MB
        print(f"Database name: {db_info['name']}, Size on Disk: {db_info['sizeOnDisk']}")

This approach can be particularly useful for maintaining large MongoDB deployments, where you’re only interested in larger databases.

Conclusion

Listing databases is a fundamental task when working with MongoDB through PyMongo. This tutorial outlined the basic through advanced techniques for listing and inspecting databases, including filtering them based on specific criteria. Understanding these techniques allows developers to efficiently manage and interact with MongoDB databases.