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

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types