Skip to content
How to connect to MongoDB
  • AI Chat
  • Code
  • Report
  • How to connect to MongoDB

    This workspace contains instructions and sample code to connect to a MongoDB database as described in this page Workspace Doc: MongoDB

    Before running the code, you need to set up some Environment Variables with your connection credentials. In the left sidebar, click on "Environment", and click on "+" next to "Environment variables".

    You need to create 3 environment variables:

    • MONGODB_HOST: Where your MongoDB cluster/database is hosted, e.g.
    • MONGODB_USERNAME: The username with which to connect to your MongoDB cluster
    • MONGODB_PASSWORD: The username's password.

    Give a meaningful name to this set of Environment variables, e.g. "MongoDB Cluster". Click Save and continue until your session is restarted to activate these environment variables.

    You can now run the code snippets below!

    !pip install pymongo
    import os
    from pymongo.mongo_client import MongoClient
    from pymongo.server_api import ServerApi
    # Get enviromental variables
    mongodb_host = os.environ["MONGODB_HOST"]
    mongodb_password = os.environ["MONGODB_PASSWORD"]
    mongodb_username = os.environ["MONGODB_USERNAME"]
    # Build a URI from the environment variables you defined before
    uri = f'mongodb+srv://{mongodb_username}:{mongodb_password}@{mongodb_host}/?retryWrites=true&w=majority'
    # Create a new client and connect to the server
    client = MongoClient(uri, server_api=ServerApi('1'))
    # Send a ping to confirm a successful connection
        print("Pinged your deployment. You successfully connected to MongoDB!")
    except Exception as e:

    For a quick overview of what PyMongo enables you to do, check out this tutorial It covers how you can get a database, a collection, find documents, insert documents, and more. Have fun!

    Additional resources:

    *** IMPORTANT NOTE ***

    Click to expand
    You need to enable in MongoDB Atlas > Project > Network Access > IP Access List allowing to these 3 DataCamp IPs: