Skip to content
Connect to MongoDB template
  • AI Chat
  • Code
  • Report
  • Spinner

    Connect to MongoDB

    This workspace contains instructions and sample code to connect to a MongoDB database.

    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:

    • MONGO_HOST: Where your MongoDB cluster/database is hosted, e.g.
    • MONGO_USER: The username with which to connect to your MongoDB cluster
    • MONGO_PASS: 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
    # Build a URI from the environment variables you defined before
    uri = f'mongodb+srv://{os.environ.get("MONGO_USER")}:{os.environ.get("MONGO_PASS")}@{os.environ.get("MONGO_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:

    You can edit this workspace to continue your work with the MongoDB you just connected. For a quick overview of what PyMongo enables you to do, check out this comprehensive tutorial. It covers how you can get a database, a collection, find documents, insert documents, and more. Have fun!