Quick Start: Getting Started With MongoDB Atlas and Python
Rate this quickstart
- How to set up MongoDB Atlas in the cloud
- How to load sample data
- How to query sample data using the PyMongo library
Sign up for Atlas and log into your account.
- You can choose any cloud instance.
- Choose the “FREE” tier.
- Follow the setup wizard and give your instance a name.
- Note your username and password to connect to the instance.
- Add 0.0.0.0/0 to the IP access list.
This makes the instance available from any IP address, which is okay for a test instance.
See the screenshot below for how to add the IP:
Next, let’s load the sample datasets available in Atlas by default. Note that loading the data may take a few minutes.
You can browse the data in the Atlas UI. Let’s look at the embedded_movies collection in the sample_mflix database. You will see that each document has details such as the title, year, plot, etc.
To connect to Atlas, we need the MongoDB connection string. Here's how you get it:
- Navigate to the Atlas UI.
- Select the database you want to connect to.
- Choose the Connect option to proceed.
- Within the connect section, click on Drivers to view connection details.
- Finally, copy the displayed connection string for use in your application's configuration.
See the below screenshots for guidance:
Once you get the connection string, assign it to a variable in your Python code:
1 ATLAS_URI = "Enter your Atlas URI value here"
We are keeping this very simple for the purpose of this quick start. For production systems, consider using libraries like python-dotenv to get configuration settings.
To connect to our Atlas cluster using the Pymongo client, we will need to install the following libraries:
1 ! pip install pymongo[srv]==4.6.2
We only need one package here:
- pymongo: Python library to connect to MongoDB Atlas.
This
AtlasClient
class will handle tasks like establishing connections, running queries, etc. It has the following methods:- init: Initializes an object of the AtlasClient class, with the MongoDB client (
mongodb_client
) and database name (database
) as attributes - ping: Used to test if we can connect to our Atlas cluster
- get_collection: The MongoDB collection to connect to
- find: Returns the results of a query; it takes the name of the collection (
collection
) to query and any search criteria (filter
) as arguments
1 from pymongo import MongoClient 2 3 class AtlasClient (): 4 5 def __init__ (self, altas_uri, dbname): 6 self.mongodb_client = MongoClient(altas_uri) 7 self.database = self.mongodb_client[dbname] 8 9 ## A quick way to test if we can connect to Atlas instance 10 def ping (self): 11 self.mongodb_client.admin.command('ping') 12 13 def get_collection (self, collection_name): 14 collection = self.database[collection_name] 15 return collection 16 17 def find (self, collection_name, filter = {}, limit=0): 18 collection = self.database[collection_name] 19 items = list(collection.find(filter=filter, limit=limit)) 20 return items
In this phase, we will establish a connection to the embedded_movies collection within the sample_mflix database. To confirm that our connection is successful, we'll perform a
ping()
operation.1 DB_NAME = 'sample_mflix' 2 COLLECTION_NAME = 'embedded_movies' 3 4 atlas_client = AtlasClient (ATLAS_URI, DB_NAME) 5 atlas_client.ping() 6 print ('Connected to Atlas instance! We are good to go!')
If you get a “Connection failed” error, make sure 0.0.0.0/0 is added as an allowed IP address to connect (see Step 1).
Let's execute a search for movies using the
find()
method. The find()
method takes two parameters. The first parameter, collection_name
, determines the specific collection to be queried — in this case, embedded_movies. The second parameter, limit
, restricts the search to return only the specified number of results — in this case, 5.1 movies = atlas_client.find (collection_name=COLLECTION_NAME, limit=5) 2 print (f"Found {len (movies)} movies") 3 4 # print out movie info 5 for idx, movie in enumerate (movies): 6 print(f'{idx+1}\nid: {movie["_id"]}\ntitle: {movie["title"]},\nyear: {movie["year"]}\nplot: {movie["plot"]}\n')
The results are returned as a list and we are simply iterating over it and printing out the results.
1 Found 5 movies 2 1 3 id: 573a1390f29313caabcd5293 4 title: The Perils of Pauline, 5 year: 1914 6 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 ... 7 8 2 9 id: 573a1391f29313caabcd68d0 10 title: From Hand to Mouth, 11 year: 1919 12 plot: A penniless young man tries to save an heiress from kidnappers and help her secure her inheritance. 13 ...
If we want to query by a certain attribute, we can pass a
filter
argument to the find()
method. filter
is a dictionary with key-value pairs. So to find movies from the year 1999, we set the filter as {"year" : 1999}
.1 movies_1999 = atlas_client.find(collection_name=COLLECTION_NAME, 2 filter={"year": 1999}
We see that 81 movies are returned as the result. Let’s print out the first few.
1 ======= Finding movies from year 1999 ========================= 2 Found 81 movies from the year 1999. Here is a sample... 3 1 4 id: 573a139af29313caabcf0cfd 5 title: Three Kings, 6 year: 1999 7 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. 8 9 2 10 id: 573a139af29313caabcf0e61 11 title: Beowulf, 12 year: 1999 13 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. 14 …
In this quick start, we learned how to set up MongoDB Atlas in the cloud, loaded some sample data into our cluster, and queried the data using the Pymongo client. To build upon what you have learned in this quickstart, here are a few more resources:
Top Comments in Forums
There are no comments on this article yet.