Python with MongoDB Atlas - CRUD

In this article, we will learn how to interact with Python and MongoDB.And we will learn to create, read, update, and delete data from the MongoDB Atlas using python.

Technologies used:
  • Python 3
  • Create an Account on MongoDB Atlas Website
  • pymongo[srv] library
Please go through the following steps in order to learn how to interact between Python and MongoDB:

Step 1. Create an Account on MongoDB Atlas
Create an account on the MongoDB Atlas website if you do not have one already. Go to https://www.mongodb.com/cloud/atlas and click Try Free green button on the top right corner to create an account.

Step 2 — Create a Starter Cluster
After you log in to your MongoDB Atlas account, you can create a starter cluster by selecting your desired cloud service provider, cluster tier, and your cluster name. It takes 1–3 mins for the cluster to be ready. When the cluster is ready, it looks like something below:
Step 3 — Click on the connect button, a popup window will show up

From this window, you can add your IP address to the configuration so that your computer can access the database. Or you can add IP address 0.0.0.0/0 to the configuration so that any IP address can access the database.

You will also need to create a MongoDB user by typing your user name and password.

Step 4. Choose a connection method


You'll get a window with different connection options; click the "Connect your application" option.

Step 5. Copy connection String


Choose Python as Driver and choose the right version of the Python you are using and you will see the connection string.

Step 6.Connecting to the cluster from a Python using the below script

import pymongo
client = pymongo.MongoClient("<the atlas connection string>")
print(client.list_database_names())
..replacing <the atlas connection string> with the actual connection string we got from the Atlas site earlier, with <password> replaced with the password you used when setting up the user.
Result:
['knforg', 'admin', 'local']
CRUD Operations
As we know in MongoDB provides our database at the top hierarchy. In the database, we store collections and inside the collections, we add documents.

Create a document
import pymongo  
client = pymongo.MongoClient("<the atlas connection string>")
collection = client.knforg.employee  
data = [  
      {  
         "id":"Sibins_1246",  
         "uname": "Sibin",  
         "email": "sibin@gmail.com",  
         "contact": "123456789122"  
      }
      ,
      {  
         "id":"Sibins_124623",  
         "uname": "Safin",  
         "email": "sibin@gmail.com",  
         "contact": "123456789122"  
      }
   ]  
collection.insert_many(data) 
print('Users Inserted Successfully')
Using collection.insert_many(data) we can able add multiple documents in collection.
 
Retrive records:
Write code in Python to retrieve records:

import pymongo  
client = pymongo.MongoClient("<the atlas connection string>")
collection = client.knforg.employee
print('Find One document')  
print(collection.find_one())  
print('Find all documents')  
for x in collection.find():  
  print(x)  
  
print('Find documents with condition')  
for x in collection.find({"uname": "Safin"}):  

  print(x)

Update document:

import pymongo  
client = pymongo.MongoClient("<the atlas connection string>")
collection = client.knforg.employee
myquery = {"uname": "Safin"}  
newvalues = {"$set": {"uname": "Sibin-123"}}   
collection.update_one(myquery, newvalues)  
print('Employee Updated Successfully') 

Delete document:

import pymongo  
client = pymongo.MongoClient("<the atlas connection string>")
collection = client.knforg.employee
myquery = {"uname": "Sibin"}  
collection.delete_one(myquery) 
print('Employee Deleted Successfully') 

                                         

More Related Topics,

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete