Skip to main content

MongoDB with Python

Prerequisites: an active MongoDB resource, an application user, Python 3 with pip, and the public connection settings. This example checks connectivity without inserting application data.

Install and configure​

python3 -m venv .venv
source .venv/bin/activate
python -m pip install pymongo

Set MONGODB_URI and MONGODB_DATABASE in your process environment. Use the exact database name and returned username. Preserve the URI’s authSource: a user created for your database should authenticate against that database, not an assumed admin database. Preserve TLS options and certificate validation.

Check the connection​

Create connect.py:

import os
from pymongo import MongoClient

with MongoClient(
os.environ["MONGODB_URI"],
serverSelectionTimeoutMS=5000,
connectTimeoutMS=5000,
) as client:
database = client[os.environ["MONGODB_DATABASE"]]
result = database.command("ping")
print(result["ok"]) # Expected: 1.0
python connect.py

A ping confirms connectivity, not permission to write every collection. Use your application’s intended read/write operation on a disposable collection to validate its assigned permissions before deployment.

Integrate into your server​

Reuse a client per process; close it during shutdown. Keep application collection names separate from the Lordbase resource UUID. Use your assigned database, not another tenant’s name or a database copied from a tutorial.

If authentication fails, check username, password encoding and authSource. If server selection times out, inspect network access, TLS, database state and the source-IP allowlist. See connection troubleshooting.

MongoDB supports database-scoped archive backups and asynchronous restore into a selected MongoDB target. Validate documents, indexes and target access in a recovery test before production use. Driver details: PyMongo connection documentation.