# Quick Start: Getting Started With MongoDB Atlas and Python

## 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:

 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:

```
! pip install pymongosrv]==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

```
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')

   def get_collection (self, collection_name):
       collection = self.database[collection_name]
       return 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 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.

```
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!')
```

> 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**.

```
movies = atlas_client.find (collection_name=COLLECTION_NAME, limit=5)
print (f"Found {len (movies)} movies")

# print out movie info
for idx, movie in enumerate (movies):
   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.

```
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.
...
```

### 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}`.

```
movies_1999 = atlas_client.find(collection_name=COLLECTION_NAME, 
                                filter={"year": 1999}
```

We see that 81 movies are returned as the result. Let’s print out the first few.

```
=======  Finding movies from year 1999 =========================
Found 81 movies from the 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.
…
```

## 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:
* [Atlas getting started guide
* Free course on MongoDB and Python
* PyMongo library documentation

  [1]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt97444a9ad37a9bb2/661434881952f0449cfc0b9b/image3.png
  [2]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt72e095b20fd4fb81/661434c7add0c9d3e85e3a52/image1.png
  [3]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt185b9d1d57e14c1f/661434f3ae80e231a5823e13/image5.png
  [4]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt02b47ac4892e6c9a/6614355eca5a972886555722/image4.png
  [5]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt661fc7099291b5de/6614357fab1db5330f658288/image2.png