[Python] How to make connection to mongodb using mongoclient

Discussão em 'Python' iniciado por Stack, Maio 13, 2025.

  1. Stack

    Stack Membro Participativo

    Background I’m trying to connect from a Python script to my MongoDB Atlas cluster using explicit TLS certificate files (the CA bundle and a client‐certificate/key pair). I downloaded the PEM files from the Atlas UI and want PyMongo to negotiate TLS with those files.

    What I’ve Tried

    here is my code

    from pymongo import MongoClient, errors
    from bson.json_util import dumps

    # ==== Configuration ====
    mongo_uri = (
    )
    mongo_db =
    mongo_collection =

    # Paths to your TLS certs
    ca_pem = "/Users/you/Downloads/"
    client_pem = "/Users/you/Downloads/"

    try:
    # 1) Establish a TLS‐secured connection
    client = MongoClient(
    mongo_uri,
    tls=True,
    tlsCAFile=ca_pem,
    tlsCertificateKeyFile=client_pem,
    retryWrites=True,
    w="majority",
    authSource="admin",
    authMechanism="SCRAM-SHA-256"
    )
    db = client[mongo_db]
    coll = db[mongo_collection]
    print(f"Connected to {mongo_db}.{mongo_collection}\n")

    # 2) Fetch and print every document
    for doc in coll.find():
    # pretty‐print with correct handling of ObjectId, dates, etc.
    print(dumps(doc, indent=2))

    except errors.PyMongoError as e:
    print(f"Error connecting to MongoDB: {e}")


    code not working giving tls not found error

    Continue reading...

Compartilhe esta Página