Database / No SQL

Mongo Manager

This is a detailed and didactic documentation of the MongoDBManager class, designed to make it easier for developers who will integrate this tool into their projects to understand it.

On this page

    #Overview

    The MongoDBManager class acts as a Wrapper (or facilitator) for the pymongo library. Its main goal is to simplify interaction with MongoDB databases, abstracting the complexity of managing connections and ensuring that common CRUD (Create, Read, Update, Delete) operations are performed in a standardized way.

    It is ideal for applications that need flexible data persistence, automatically handling metadata such as creation and update dates.

    #Execution Flow

    The class follows a Lazy Loading logic:

    1. Instantiation: When the object is created, it only stores the connection URI. The database is not accessed yet.
    2. First Call: When any operation method (such as save_payload) is invoked, it internally calls the connect() method.
    3. Persistent Connection: The MongoClient is created and stored in the self.client attribute. All subsequent calls reuse this same connection to save resources.
    4. Processing: The method runs the requested logic (insert, search, etc.).
    5. Error Handling: If something fails, the connection is closed preventively to avoid memory leaks or "stuck" connections.

    #Methods Table

    MethodBrief Description
    __init__Configures the connection URI (via argument or environment variable).
    connectEstablishes or reuses the connection to the MongoDB server.
    close_connectionEnds the active connection and clears the client.
    save_payloadInserts a new document with a creation timestamp.
    fetch_documentsSearches documents with filters and a limit option.
    update_documentsUpdates one or several records, adding an edit timestamp.
    delete_documentsPermanently removes records from the database.

    #Architecture and Insights

    • State Management: The class uses a Singleton-like pattern for the connection within the instance, ensuring you do not open hundreds of unnecessary connections.
    • Data Safety: In the update method, the code explicitly removes the _id key from the update payload (new_values.pop("_id", None)). This avoids common MongoDB errors caused by trying to overwrite a document's immutable ID.
    • Traceability: The automatic inclusion of _created_at and updated_at turns simple documents into auditable records, making later debugging and data analysis easier.
    • Error Handling: The use of RuntimeError wraps complex network errors in messages that are readable for the application developer.

    #Class Details

    #MongoDBManager Class

    Description

    Central MongoDB persistence manager that encapsulates the connection lifecycle and CRUD operations, ensuring resource reuse and metadata standardization.

    Arguments

    • mongo_uri (str, optional): Connection string. If omitted, it looks up os.getenv("MONGO_URI") or uses the local default.

    #Methods

    #1. connect

    Description: Ensures that there is an active connection to the database.

    Arguments: None.

    Returns: MongoClient (pymongo connection object).

    Raises: Exception in case of network or credentials failure.

    Examples:

    manager = MongoDBManager()
    client = manager.connect()

    #2. save_payload

    Description: Inserts a dictionary into the database and adds the creation date.

    Arguments:

    • database_name (str): Name of the database.
    • collection_name (str): Name of the collection.
    • payload (dict): Data to be saved.

    Returns: dict containing the status and the generated ID.

    Raises: RuntimeError if the insert fails.

    Examples:

    manager.save_payload("log_db", "events", {"event": "login_success"})

    #3. fetch_documents

    Description: Locates documents that match the given criteria.

    Arguments:

    • database_name (str): Name of the database.
    • collection_name (str): Name of the collection.
    • filter (dict): Search filter (e.g. {"status": "active"}).
    • limit (int): Maximum number of results.

    Returns: List[dict] (List of documents found).

    Raises: RuntimeError.

    Examples:

    users = manager.fetch_documents("app", "users", {"age": {"$gt": 18}}, limit=10)

    #4. update_documents

    Description: Modifies existing documents and records the modification date.

    Arguments:

    • filter (dict): Criterion to find the documents.
    • new_values (dict): Data to be updated.
    • multi (bool): If True, updates all documents found; if False, only the first.

    Returns: dict with metrics (matched_count, modified_count).

    Raises: RuntimeError.

    Examples:

    manager.update_documents("app", "users", {"id": 1}, {"status": "premium"})

    #5. delete_documents

    Description: Permanently removes documents from the collection.

    Arguments:

    • filter (dict): Deletion criterion.
    • multi (bool): Defines whether to delete one or all the records found.

    Returns: dict with deleted_count.

    Raises: RuntimeError.

    Examples:

    manager.delete_documents("app", "temp_data", {"expired": True}, multi=True)

    Source: src/database/no_relational_db/mongo_manager.py

    Esc
    ↑↓navigate Enteropen