Python, MongoDB, and Compose

Installing the Driver

The recommended python driver for MongoDB is PyMongo.
The current PyMongo version can be installed through pip:
pip install pymongo

Full-example Code

import os
import pymongo
import ssl

MONGODB_URL = os.environ.get('MONGODB_URL')

    client = pymongo.MongoClient(
    client = pymongo.MongoClient(

db = client.get_default_database()
print (db.collection_names())

TLS/SSL and Authentication

PyMongo can parse the connection string that Compose provides on the Overview page of your deployment. For use in these examples, the connection string is set in an environment variable MONGODB_URL. For example:

export MONGODB_URL = "mongodb://admin:[password],"

The driver will automatically pull the username and password from the connection string.

Self-signed Certificates

If your deployment has self-signed certificates, you will need to save a local copy of the certificate. Then you will provide the driver with the path to that certificate. For these examples the path is set in an environment variable MONGODB_CERT_PATH.

export MONGODB_CERT_PATH= "/Path/to_the/cert/mongo_cert.pem"

Database Connection

In addition to connection information, the driver will also look for a database to connect to. Connect to the default database on your deployment using
db = client.get_default_database().
You can specify a database to connect to using
db = client.my_database.

More Information

Still Need Help?

If this article didn't solve things, summon a human and get some help!