Sling Academy
Home/Python/PyMongo: How to establish/close a connection

PyMongo: How to establish/close a connection

Last updated: February 06, 2024

Introduction

PyMongo is a Python distribution containing tools for working with MongoDB, and is the recommended way to work with MongoDB from Python. It provides a simple way for Python applications to interact with MongoDB using a straightforward API. In this tutorial, we will explore how to establish and close a connection to a MongoDB database using PyMongo, moving from the basics to more advanced concepts, including error handling and using context managers.

Prerequisites

Before we dive into the code, ensure you have the following installed on your machine:

  • Python (version 3.6 or later is preferred)
  • MongoDB (Follow the official MongoDB documentation for installation instructions)
  • PyMongo (Install by running pip install pymongo)

Basic Connection

Establishing a basic connection to MongoDB using PyMongo is straightforward. First, you need to import MongoClient from PyMongo, then use it to connect to the MongoDB server. Here’s how:

from pymongo import MongoClient

# Establish a connection to the MongoDB server
default_connection = MongoClient('localhost', 27017)

print('Connection established: ', default_connection)

This code connects to a MongoDB server running on localhost on the default MongoDB port (27017). The print statement confirms that the connection has been established.

Specifying a Database

Once connected, you might want to specify which database within MongoDB you wish to interact with. This can be achieved easily:

db = default_connection.mydatabase

print('Database selected: ', db.name)

This code selects a database named ‘mydatabase’. If the database does not exist, MongoDB will create it for you as soon as you try to insert some data.

Authentication

In real-world applications, databases are secured with authentication. PyMongo makes it straightforward to connect to authenticated databases:

secure_connection = MongoClient('localhost', 27017,
                              username='myUser',
                              password='myPassword',
                              authSource='theDatabase')

print('Authenticated connection established')

Note: Replace ‘myUser’, ‘myPassword’, and ‘theDatabase’ with your actual MongoDB username, password, and the database you are authenticating against.

Error Handling

It’s important to manage errors effectively when establishing connections, especially concerning authentication or network issues. PyMongo throws exceptions that can be caught and handled:

try:
    connection = MongoClient('nonexistenthost', 27017)
except Exception as e:
    print(f'Error connecting to MongoDB: {e}')

This code attempts to establish a connection to an invalid host, catching and reporting any exceptions.

Using with Statement (Context Managers)

Python’s with statement simplifies resource management, automatically handling the opening and closing of resources. While PyMongo’s MongoClient doesn’t support context management natively, you can easily create a context manager:

class MongoDBConnectionManager():
    def __enter__(self):
        self.connection = MongoClient('localhost', 27017)
        return self.connection

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.connection.close()

with MongoDBConnectionManager() as connection:
    db = connection.mydatabase
    # Perform database operations

In this approach, the connection is automatically closed when exiting the block, ensuring resources are properly managed and reducing the risk of leaks.

Advanced Usage: Connection Pooling and Timeout

For more complex applications, managing connection pooling and timeouts becomes critical. PyMongo provides options to control these:

from pymongo import MongoClient

client = MongoClient('localhost', 27017,
                      maxPoolSize=50, connectTimeoutMS=3000)

# This enhances performance by managing multiple connections and setting a connect timeout.

These options help manage the performance of your interactions with MongoDB, ensuring scalability and robustness.

Conclusion

PyMongo offers a simple yet powerful API for interacting with MongoDB databases. Whether you’re establishing a basic connection or dealing with advanced configurations, PyMongo equips you with the tools you need. Remember, properly closing your connections is as important as establishing them, ensuring your applications run efficiently and securely.

Next Article: PyMongo: How to use a connection pool

Previous Article: Python sqlite3: Working with multiple databases

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