Explore Developer Center's New Chatbot! MongoDB AI Chatbot can be accessed at the top of your navigation to answer all your MongoDB questions.

Join us at AWS re:Invent 2024! Learn how to use MongoDB for AI use cases.
MongoDB Developer
Atlas
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Productschevron-right
Atlaschevron-right

Quick Start: Getting Started With MongoDB Atlas and Python

SM
Sujee Maniyam4 min read • Published Apr 09, 2024 • Updated Apr 10, 2024
AtlasPython
Facebook Icontwitter iconlinkedin icon
Rate this quickstart
star-empty
star-empty
star-empty
star-empty
star-empty

What you will learn

  • How to set up MongoDB Atlas in the cloud
  • How to load sample data
  • How to query sample data using the PyMongo library

Where's the code?

The Jupyter Notebook for this quickstart tutorial can be found here.

Step 1: Set up MongoDB Atlas

Here is a quick guide adopted from the official documentation:

Create a free Atlas account

Sign up for Atlas and log into your account.

Create a free instance

  • 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:
Editing Network Access settings in the MongoDB Atlas UI

Load sample data

Next, let’s load the sample datasets available in Atlas by default. Note that loading the data may take a few minutes.
Loading sample datasets in the MongoDB Atlas UI

View sample data

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.
Viewing sample data in the MongoDB Atlas UI

Step 2: Setup prerequisites

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:
enter image description here
Obtaining the connection string from the MongoDB Atlas UI
Once you get the connection string, assign it to a variable in your Python code:
1ATLAS_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.

Step 3: Install the required libraries

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.

Step 4: Define the AtlasClient class

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
1from pymongo import MongoClient
2
3class 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

Step 5: Connect to MongoDB Atlas

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.
1DB_NAME = 'sample_mflix'
2COLLECTION_NAME = 'embedded_movies'
3
4atlas_client = AtlasClient (ATLAS_URI, DB_NAME)
5atlas_client.ping()
6print ('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).

Step 6: Run a sample query

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.
1movies = atlas_client.find (collection_name=COLLECTION_NAME, limit=5)
2print (f"Found {len (movies)} movies")
3
4# print out movie info
5for 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.
1Found 5 movies
21
3id: 573a1390f29313caabcd5293
4title: The Perils of Pauline,
5year: 1914
6plot: 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
82
9id: 573a1391f29313caabcd68d0
10title: From Hand to Mouth,
11year: 1919
12plot: A penniless young man tries to save an heiress from kidnappers and help her secure her inheritance.
13...

Query by an attribute

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}.
1movies_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 =========================
2Found 81 movies from the year 1999. Here is a sample...
31
4id: 573a139af29313caabcf0cfd
5title: Three Kings,
6year: 1999
7plot: 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
92
10id: 573a139af29313caabcf0e61
11title: Beowulf,
12year: 1999
13plot: 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

Conclusion

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.
Start the Conversation

Facebook Icontwitter iconlinkedin icon
Rate this quickstart
star-empty
star-empty
star-empty
star-empty
star-empty
Related
News & Announcements

RAG Made Easy with MongoDB Atlas and Azure OpenAI


Nov 20, 2024 | 4 min read
Tutorial

How to Deploy MongoDB Atlas with Terraform on AWS


Jan 23, 2024 | 12 min read
Tutorial

MongoDB Data Federation Setup


Jan 23, 2024 | 5 min read
Tutorial

Using the Node.js MongoDB Driver with AWS Lambda


Jan 23, 2024 | 5 min read
Table of Contents