Use PyMongo to connect to DocumentDB, verify authentication and TLS, and run your first document queries from Python.
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.
python3 -m venv .venv
source .venv/bin/activateIf you do not use a virtual environment, run the next commands with the Python interpreter you plan to use for your app.
python -m pip install pymongoPyMongo already includes the bson package it needs. Do not install the separate bson package from PyPI.
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.pyYou should see the recent movie documents printed after a successful ping.
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)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.pemclient = MongoClient(
"mongodb://<YOUR_USERNAME>:<YOUR_PASSWORD>@localhost:10260/?tls=true",
tlsCAFile="/absolute/path/documentdb-cert.pem",
)If the Python quick start does not work on the first try:
docker ps --filter "name=documentdb" and docker logs documentdbsudo systemctl status documentdb-gateway and sudo journalctl -u documentdb-gateway --no-pager -n 50pymongo, verify the active interpreter with python -c "import sys; print(sys.executable)" and reinstall with python -m pip install pymongotlsAllowInvalidCertificates=true or switch to a trusted local certificate with tlsCAFile