Python Quick Start

Use PyMongo to connect to DocumentDB, verify authentication and TLS, and run your first document queries from Python.

Prerequisites

Start DocumentDB first

For the fastest local setup, start DocumentDB Local with Docker:

docker run -dt --name documentdb \
  -p 10260:10260 \
  ghcr.io/documentdb/documentdb/documentdb-local:latest \
  --username <YOUR_USERNAME> \
  --password <YOUR_PASSWORD>

If you prefer a host installation instead of Docker, use Linux Packages Quick Start and complete the documentdb-setup step first.

DocumentDB Local uses a self-signed certificate by default, so the quickest local PyMongo connection uses tlsAllowInvalidCertificates=true.

Create a virtual environment (optional)

python3 -m venv .venv
source .venv/bin/activate

If you do not use a virtual environment, run the next commands with the Python interpreter you plan to use for your app.

Install PyMongo

python -m pip install pymongo

PyMongo already includes the bson package it needs. Do not install the separate bson package from PyPI.

Connect and run your first queries

Create a quickstart.py file:

from pymongo import MongoClient

uri = (
    "mongodb://<YOUR_USERNAME>:<YOUR_PASSWORD>@localhost:10260/"
    "?tls=true&tlsAllowInvalidCertificates=true"
)

client = MongoClient(uri)

try:
    client.admin.command("ping")

    db = client["quickstart"]
    movies = db["movies"]

    movies.delete_many({})
    movies.insert_many(
        [
            {"title": "The Matrix", "year": 1999, "genres": ["sci-fi", "action"]},
            {"title": "Dune", "year": 2021, "genres": ["sci-fi", "adventure"]},
            {"title": "Arrival", "year": 2016, "genres": ["sci-fi", "drama"]},
        ]
    )

    movies.create_index("title")

    for movie in movies.find(
        {"year": {"$gte": 2000}},
        {"_id": 0, "title": 1, "year": 1},
    ).sort("year", -1):
        print(movie)
finally:
    client.close()

Run the script:

python quickstart.py

You should see the recent movie documents printed after a successful ping.

Explore the built-in sample data

If you started with DocumentDB Local sample data, add this snippet after client.admin.command("ping"):

for user in client["sampledb"]["users"].find(
    {},
    {"_id": 0, "name": 1, "email": 1},
).limit(3):
    print(user)

Use a trusted local certificate instead

If you want certificate validation instead of tlsAllowInvalidCertificates=true, copy the generated certificate from the container and pass it to MongoClient.

docker cp documentdb:/home/documentdb/gateway/pg_documentdb_gw/cert.pem ~/documentdb-cert.pem
client = MongoClient(
    "mongodb://<YOUR_USERNAME>:<YOUR_PASSWORD>@localhost:10260/?tls=true",
    tlsCAFile="/absolute/path/documentdb-cert.pem",
)

Troubleshooting and debugging

If the Python quick start does not work on the first try:

  • Verify your local DocumentDB instance is running before you start Python
  • If you used Docker, check docker ps --filter "name=documentdb" and docker logs documentdb
  • If you used Linux packages, check sudo systemctl status documentdb-gateway and sudo journalctl -u documentdb-gateway --no-pager -n 50
  • If Python cannot import pymongo, verify the active interpreter with python -c "import sys; print(sys.executable)" and reinstall with python -m pip install pymongo
  • If you see TLS or certificate errors, either use the default local self-signed flow with tlsAllowInvalidCertificates=true or switch to a trusted local certificate with tlsCAFile
  • Use Mongo Shell Quick Start to validate the endpoint independently of your application code