Interaction between Python and MongoDB Atlas

Interaction between Python and MongoDB Atlas

In this post, we are going to develop an interaction between Python and MongoDB

In this post, we are going to develop an interaction between Python and MongoDB. 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.

This is image title

You will see a popup with three options. We will explore each option.

This is image title

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

This is image title

From drivers, select Python and the latest version after that. Copy the connection string only.

This is image title

mongodb+srv://admin:@cluster0-kbpys.mongodb.net/test?retryWrites=true&w=majority

Note

You need to replace the actual password with

Now open any Python editor. I am using PyCharm.

Start development

First, open pycharm.

Create an open sample project.

Open a terminal in pycharm.

This is image title

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.

import pymongo  
client = pymongo.MongoClient("<the atlas connection string>")  

Copy the connection string from Atlas and paste it here.

import pymongo  
client = pymongo.MongoClient("mongodb+srv://admin:[email protected]/test?retryWrites=true&w=majority")  
for name in client.list_database_names():  
    print(name)  

The output should look like:

This is image title

Now we try to list the database and respective collections.

import pymongo  
client = pymongo.MongoClient("mongodb+srv://admin:[email protected]/test?retryWrites=true&w=majority")  

for database_name in client.list_database_names():  
    print("Database - "+database_name)  
    for collection_name in client.get_database(database_name).list_collection_names():  
        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.

import pymongo  
client = pymongo.MongoClient("mongodb+srv://admin:[email protected]/test?retryWrites=true&w=majority")  

collection = client.libraryDB.books  
booksData = [  

      {  
         "id":"01",  
         "language": "Java",  
         "edition": "third",  
         "author": "Herbert Schildt"  
      },  

      {  
         "id":"07",  
         "language": "C++",  
         "edition": "second",  
         "author": "E.Balagurusamy"  
      }  
   ]  

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.

This is image title

And press the COLLECTIONS button.

This is image title

Option 2

Write code in Python to retrieve records:

print('Find One document')  
print(client.libraryDB.books.find_one())  

print('Find all documents')  
for x in client.libraryDB.books.find():  
  print(x)  

print('Find documents with condition')  
for x in client.libraryDB.books.find({"language": "Java"}):  
  print(x)  

Update document

myquery = {"language": "Advanced Java"}  
newvalues = {"$set": {"language": "Java"}}  

client.libraryDB.books.update_one(myquery, newvalues)  

Delete document

myquery = {"language": "Java"}  
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
Index Types
Single Field
collection.create_index([('name', 1)])

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.

client.libraryDB.books.aggregate([  
   { $match: { 'language': 'Java' } },  
   { $group: { _id: "$cust_id", total: { "$sum": "$amount" } } }  
])  

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:

Thank you for reading!

python mongodb developer programming

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Top Python Development Companies | Hire Python Developers

After analyzing clients and market requirements, TopDevelopers has come up with the list of the best Python service providers. These top-rated Python developers are widely appreciated for their professionalism in handling diverse projects. When...

Guide to Python Programming Language

Guide to Python Programming Language

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Python Hello World Program - Create & Run Your First Python Program in PyCharm

Python Hello World Program - Your first step towards Python world. Learn how to create the Hello World Python program in PyCharm.

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners