Sling Academy
Home/Python/PyMongo: How to List All Databases

PyMongo: How to List All Databases

Last updated: February 06, 2024

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.

Next Article: PyMongo: How to list all collections in a database

Previous Article: PyMongo: How to use a connection pool

Series: Data Persistence in Python – Tutorials & Examples

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots