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.

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

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

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

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.

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:

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.

And press the COLLECTIONS button.

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!

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

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

What’s new in HTML6

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

What is new features in Javascript ES2020 ECMAScript 2020

Top Python Development Companies | Hire Python Developers

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

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 you look for the developer in hurry you may forget to take note of review and ratings of the company's aspects, but we at TopDevelopers have done a clear analysis of these top reviewed Python development companies listed here and have picked the best ones for you.

List of Best Python Web Development Companies & Expert Python Programmers.

Guide to Python Programming Language

Guide to Python Programming Language

Guide to Python Programming Language

Description
The course will lead you from beginning level to advance in Python Programming Language. You do not need any prior knowledge on Python or any programming language or even programming to join the course and become an expert on the topic.

The course is begin continuously developing by adding lectures regularly.

Please see the Promo and free sample video to get to know more.

Hope you will enjoy it.

Basic knowledge
An Enthusiast Mind
A Computer
Basic Knowledge To Use Computer
Internet Connection
What will you learn
Will Be Expert On Python Programming Language
Build Application On Python Programming Language

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Description
Hello and welcome to brand new series of wiredwiki. In this series i will teach you guys all you need to know about python. This series is designed for beginners but that doesn't means that i will not talk about the advanced stuff as well.

As you may all know by now that my approach of teaching is very simple and straightforward.In this series i will be talking about the all the things you need to know to jump start you python programming skills. This series is designed for noobs who are totally new to programming, so if you don't know any thing about

programming than this is the way to go guys Here is the links to all the videos that i will upload in this whole series.

In this video i will talk about all the basic introduction you need to know about python, which python version to choose, how to install python, how to get around with the interface, how to code your first program. Than we will talk about operators, expressions, numbers, strings, boo leans, lists, dictionaries, tuples and than inputs in python. With

Lots of exercises and more fun stuff, let's get started.

Download free Exercise files.

Dropbox: https://bit.ly/2AW7FYF

Who is the target audience?

First time Python programmers
Students and Teachers
IT pros who want to learn to code
Aspiring data scientists who want to add Python to their tool arsenal
Basic knowledge
Students should be comfortable working in the PC or Mac operating system
What will you learn
know basic programming concept and skill
build 6 text-based application using python
be able to learn other programming languages
be able to build sophisticated system using python in the future

To know more: