Skip to content

*** IMPORTANT NOTE ***

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


Requires the PyMongo package.

https://www.mongodb.com/docs/drivers/pymongo/

!pip install --upgrade pymongo
Hidden output
import os
from datetime import datetime, tzinfo, timezone
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
from bson import ObjectId
MongoClient
ServerApi
Get environment variables
mongodb_host = os.environ["MONGODB_HOST"]
mongodb_username = os.environ["MONGODB_USERNAME"]
mongodb_password = os.environ["MONGODB_PASSWORD"]
Set the connection string using the environment variables
MONGODB_CONNECTION_STRING = f'mongodb+srv://{mongodb_username}:{mongodb_password}@{mongodb_host}/??retryWrites=true&w=majority'

Connect to MongoDB

CLIENT = MongoClient(MONGODB_CONNECTION_STRING, server_api=ServerApi('1'))
CLIENT
try:
    CLIENT.admin.command('ping')
    print("Pinged your deployment. You successfully connected to MongoDB!")
except Exception as e:
    print(e)

Set the database and collection names to run against