MongoDB
To work with data in a MongoDB database, you first need to create a set of Environment Variables to securely store the connection credentials. Next, you can write some Python code to establish a connection and run queries.
Create a new Python workspace (or duplicate this workspace that already has all the Python code you'll need in the next step).
In your new workspace, 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. test-cluster.t6rcsje.mongodb.net.MONGO_USER
: The username with which to connect to your MongoDB clusterMONGO_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.

Set up environent variables.
Create a new Python cell and include the following code snippet to create a new Mongo client that connects to the database. Notice how the environment variables are fetched from the environment using
os.environ
.!pip install pymongo
import os
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
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'))
You can now run queries! To start, you can do a ping command to verify that the connection works fine:
try:
client.admin.command('ping')
print("Pinged your deployment. You successfully connected to MongoDB!")
except Exception as e:
print(e)
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.
Last modified 1mo ago