PyMongo: How to establish/close a connection

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

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.