MongoDB Atlas with Python

Introduction

 
In this article, we are going to develop an interaction between Python and MongoDB. 
 
In another article, we set up a MongoDB Atlas account and also completed some basic exercises in Mongo DB, such as creating a database, creating a collection and inserting some documents as well. If you are interested, then please go through this article before starting.
 
Before beginning this, I am expecting that you should aware of the basics of Python. This article is not covering Python installation and setup
 

Atlas Setup

 
First, open the mongodb Atlas in a browser.
 
Select cluster from the left panel.
 
And press the CONNECT button.
 
MongoDB Atlas with Python
 
You will see a popup with three options. We will explore each option.
 
MongoDB Atlas with Python 
 
Here, we will choose the “Connect to your Application” option
 
We will get a popup with 2 options:
  • DRIVERS and VERSIONS
  • Connection String or Full driver example
     
    MongoDB Atlas with Python
From drivers, select Python and the latest version after that. Copy the connection string only.
 
MongoDB Atlas with Python 
 
mongodb+srv://admin:<password>@cluster0-kbpys.mongodb.net/test?retryWrites=true&w=majority
 
Note
 
You need to replace the actual password with <password>
 
Now open any Python editor. I am using PyCharm.
 
Start development
 
First, open pycharm.
 
Create an open sample project.
 
Open a terminal in pycharm.
 
MongoDB Atlas with Python
 
Now install mongodb dependencies for python from the terminal.
 
pip3 install pymongo[srv]
 
Create one sample py file, mongo_atlas_database.py
 
Here we are going to print all databases and also add one database.
  1. import pymongo  
  2. client = pymongo.MongoClient("<the atlas connection string>")  
Copy the connection string from Atlas and paste it here.
  1. import pymongo  
  2. client = pymongo.MongoClient("mongodb+srv://admin:admin123@cluster0-kbpys.mongodb.net/test?retryWrites=true&w=majority")  
  3. for name in client.list_database_names():  
  4.     print(name)  
The output should look like:
 
MongoDB Atlas with Python 
 
Now we try to list the database and respective collections.
  1. import pymongo  
  2. client = pymongo.MongoClient("mongodb+srv://admin:admin123@cluster0-kbpys.mongodb.net/test?retryWrites=true&w=majority")  
  3.   
  4. for database_name in client.list_database_names():  
  5.     print("Database - "+database_name)  
  6.     for collection_name in client.get_database(database_name).list_collection_names():  
  7.         print(collection_name)  

CRUD Operations

 
As we know in mongodb provides us database at the top hierarchy. In the database, we store collections and inside the collections, we add documents.
 
Create document
First, we create a database.
  1. import pymongo  
  2. client = pymongo.MongoClient("mongodb+srv://admin:admin123@cluster0-kbpys.mongodb.net/test?retryWrites=true&w=majority")  
  3.   
  4. collection = client.libraryDB.books  
  5. booksData = [  
  6.   
  7.       {  
  8.          "id":"01",  
  9.          "language""Java",  
  10.          "edition""third",  
  11.          "author""Herbert Schildt"  
  12.       },  
  13.   
  14.       {  
  15.          "id":"07",  
  16.          "language""C++",  
  17.          "edition""second",  
  18.          "author""E.Balagurusamy"  
  19.       }  
  20.    ]  
  21.   
  22. collection.insert_many(booksData)  
Using collection.insert_many(booksData) we can able add multiple documents in collection.
 
View document
 
To verify the documents are added or not, we have two options.
 
Option 1 - View documents in MongoDB atlas 
 
Select cluster from the left panel.
 
MongoDB Atlas with Python 
 
And press the COLLECTIONS button.
 
MongoDB Atlas with Python 
 
Option 2
 
Write code in Python to retrieve records:
  1. print('Find One document')  
  2. print(client.libraryDB.books.find_one())  
  3.   
  4. print('Find all documents')  
  5. for x in client.libraryDB.books.find():  
  6.   print(x)  
  7.   
  8. print('Find documents with condition')  
  9. for x in client.libraryDB.books.find({"language""Java"}):  
  10.   print(x)  
Update document
  1. myquery = {"language""Advanced Java"}  
  2. newvalues = {"$set": {"language""Java"}}  
  3.   
  4. client.libraryDB.books.update_one(myquery, newvalues)  
Delete document
  1. myquery = {"language""Java"}  
  2. client.libraryDB.books.delete_one(myquery)  
Indexing
 
Indexing is used to improve the performance while retrieving the documents
 
client.libraryDB.books.create_index([('name', 1)])
 
1: Ascending
-1: Descending
  1. Index Types
    1. Single Field
       collection.create_index([('name', 1)]) 
    2. Compound Index
       client.libraryDB.books.createIndex( { <field1>: <type>, <field2>: <type2>, ... } )

Aggregation

 
Aggregation operations process data records and also return computed results. Aggregation operations group values from multiple documents together and can perform a variety of operations on the grouped data to return a single result. So, complex computations can easily handle by aggregation.
  1. client.libraryDB.books.aggregate([  
  2.    { $match: { 'language''Java' } },  
  3.    { $group: { _id: "$cust_id", total: { "$sum""$amount" } } }  
  4. ])  

Summary

 
We have learned some writing with simple CRUD operations, then we learned the concept of indexing and the use of aggregation. If you need more information, then please go through the below links: