Getting Started with MongoDB Atlas and Python¶
This notebook shows how to quickly get started with MongoDB Atlas and Python.
Step 1: Pre-requisites¶
Follow the steps in the tutorial to get the MongoDB Atlas connection string and set it here.
In [12]:
Copied!
ATLAS_URI = "mongodb+srv://joernsteffen:wiiEEzyotdDxgYhH@cluster0.2xgk0.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0"
ATLAS_URI = "mongodb+srv://joernsteffen:wiiEEzyotdDxgYhH@cluster0.2xgk0.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0"
Step 2: Install dependencies¶
pymongo: Python client to interact with MongoDB Atlas
In [13]:
Copied!
! pip install -qU pymongo==4.6.2
! python -m pip install "pymongo[srv]"==3.12
! pip install -qU pymongo==4.6.2
! python -m pip install "pymongo[srv]"==3.12
Collecting pymongo==3.12 (from pymongo[srv]==3.12)
Using cached pymongo-3.12.0-cp310-cp310-linux_x86_64.whl
Requirement already satisfied: dnspython<2.0.0,>=1.16.0 in /usr/local/lib/python3.10/dist-packages (from pymongo[srv]==3.12) (1.16.0)
Installing collected packages: pymongo
Attempting uninstall: pymongo
Found existing installation: pymongo 4.6.2
Uninstalling pymongo-4.6.2:
Successfully uninstalled pymongo-4.6.2
Successfully installed pymongo-3.12.0
Step 3: Define the AtlasClient class¶
Handy class that has common Atlas functions.
In [15]:
Copied!
from pymongo import MongoClient
class AtlasClient:
def __init__(self, altas_uri, dbname):
self.mongodb_client = MongoClient(altas_uri)
self.database = self.mongodb_client[dbname]
# A quick way to test if we can connect to Atlas instance
def ping(self):
self.mongodb_client.admin.command("ping")
# Get the MongoDB Atlas collection to connect to
def get_collection(self, collection_name):
collection = self.database[collection_name]
return collection
# Query a MongoDB collection
def find(self, collection_name, filter={}, limit=0):
collection = self.database[collection_name]
items = list(collection.find(filter=filter, limit=limit))
return items
from pymongo import MongoClient
class AtlasClient:
def __init__(self, altas_uri, dbname):
self.mongodb_client = MongoClient(altas_uri)
self.database = self.mongodb_client[dbname]
# A quick way to test if we can connect to Atlas instance
def ping(self):
self.mongodb_client.admin.command("ping")
# Get the MongoDB Atlas collection to connect to
def get_collection(self, collection_name):
collection = self.database[collection_name]
return collection
# Query a MongoDB collection
def find(self, collection_name, filter={}, limit=0):
collection = self.database[collection_name]
items = list(collection.find(filter=filter, limit=limit))
return items
Step 4: Connect to MongoDB Atlas¶
Check if we can connect to our MongoDB collection.
If this step fails, make sure Connect From Anywhere is enabled on your Atlas network configuration (See Step 1 in the tutorial).
In [16]:
Copied!
DB_NAME = "sample_mflix"
COLLECTION_NAME = "embedded_movies"
atlas_client = AtlasClient(ATLAS_URI, DB_NAME)
atlas_client.ping()
print("Connected to Atlas instance! We are good to go!")
DB_NAME = "sample_mflix"
COLLECTION_NAME = "embedded_movies"
atlas_client = AtlasClient(ATLAS_URI, DB_NAME)
atlas_client.ping()
print("Connected to Atlas instance! We are good to go!")
Connected to Atlas instance! We are good to go!
Step 5: Run a sample query¶
Now that we are connected to our instance. Let's try some queries
In [17]:
Copied!
print("======== Finding some sample movies ========================")
movies = atlas_client.find(collection_name=COLLECTION_NAME, limit=5)
print(f"Found {len (movies)} movies")
for idx, movie in enumerate(movies):
print(
f'{idx+1}\nid: {movie["_id"]}\ntitle: {movie["title"]},\nyear: {movie["year"]}\nplot: {movie["plot"]}\n'
)
print("================================")
print("======== Finding some sample movies ========================")
movies = atlas_client.find(collection_name=COLLECTION_NAME, limit=5)
print(f"Found {len (movies)} movies")
for idx, movie in enumerate(movies):
print(
f'{idx+1}\nid: {movie["_id"]}\ntitle: {movie["title"]},\nyear: {movie["year"]}\nplot: {movie["plot"]}\n'
)
print("================================")
======== Finding some sample movies ======================== Found 5 movies 1 id: 573a1390f29313caabcd5293 title: The Perils of Pauline, year: 1914 plot: Young Pauline is left a lot of money when her wealthy uncle dies. However, her uncle's secretary has been named as her guardian until she marries, at which time she will officially take ... 2 id: 573a1391f29313caabcd68d0 title: From Hand to Mouth, year: 1919 plot: A penniless young man tries to save an heiress from kidnappers and help her secure her inheritance. 3 id: 573a1391f29313caabcd820b title: Beau Geste, year: 1926 plot: Michael "Beau" Geste leaves England in disgrace and joins the infamous French Foreign Legion. He is reunited with his two brothers in North Africa, where they face greater danger from their... 4 id: 573a1391f29313caabcd8268 title: The Black Pirate, year: 1926 plot: Seeking revenge, an athletic young man joins the pirate band responsible for his father's death. 5 id: 573a1391f29313caabcd8319 title: For Heaven's Sake, year: 1926 plot: An irresponsible young millionaire changes his tune when he falls for the daughter of a downtown minister. ================================
Query by an attribute¶
Let's find movies came out in year 1999, by passing a filter to the find method.
In [18]:
Copied!
print("======= Finding movies from year 1999 =========================")
movies_1999 = atlas_client.find(collection_name=COLLECTION_NAME, filter={"year": 1999})
print(f"Found {len (movies_1999)} movies from year 1999. Here is a sample...")
for idx, movie in enumerate(movies_1999[:5]):
print(
f'{idx+1}\nid: {movie["_id"]}\ntitle: {movie["title"]},\nyear: {movie["year"]}\nplot: {movie["plot"]}\n'
)
print("======= Finding movies from year 1999 =========================")
movies_1999 = atlas_client.find(collection_name=COLLECTION_NAME, filter={"year": 1999})
print(f"Found {len (movies_1999)} movies from year 1999. Here is a sample...")
for idx, movie in enumerate(movies_1999[:5]):
print(
f'{idx+1}\nid: {movie["_id"]}\ntitle: {movie["title"]},\nyear: {movie["year"]}\nplot: {movie["plot"]}\n'
)
======= Finding movies from year 1999 ========================= Found 81 movies from year 1999. Here is a sample... 1 id: 573a139af29313caabcf0cfd title: Three Kings, year: 1999 plot: In the aftermath of the Persian Gulf War, 4 soldiers set out to steal gold that was stolen from Kuwait, but they discover people who desperately need their help. 2 id: 573a139af29313caabcf0e61 title: Beowulf, year: 1999 plot: A sci-fi update of the famous 6th Century poem. In a beseiged land, Beowulf must battle against the hideous creature Grendel and his vengeance seeking mother. 3 id: 573a139af29313caabcf0e6c title: The Mummy, year: 1999 plot: An American serving in the French Foreign Legion on an archaeological dig at the ancient city of Hamunaptra accidentally awakens a Mummy. 4 id: 573a139af29313caabcf0e95 title: The 13th Warrior, year: 1999 plot: A man, having fallen in love with the wrong woman, is sent by the sultan himself on a diplomatic mission to a distant land as an ambassador. Stopping at a Viking village port to restock on supplies, he finds himself unwittingly embroiled on a quest to banish a mysterious threat in a distant Viking land. 5 id: 573a139af29313caabcf0edf title: The Mod Squad, year: 1999 plot: Three minor delinquints (Danes, Ribisi, and Epps) are recruited by a cop (Farina) working undercover to bust a cop/drug ring. When the officer who recruited them is killed, they go above ...