How to Work with NoSQL Database in Python using PyMongo

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

1. Python NoSQL Database

In our last Python tutorial, we studied Python Database Access. Here, in this Python NoSQL Database tutorial, we will study the working of NoSQL Database in Python Programming Language. In addition, we will discuss the need and benefits of Python NoSQL Database. Along with this will study different types of NoSQL and different function like how to insert into, update, and delete data from a NoSQL database. We will use MongoDB for this. At last, we will cover the NoSQL vs SQL.

So, let’s start the NoSQL Database in Python.

How to Work with NoSQL Database in Python using PyMongo

How to Work with NoSQL Database in Python using PyMongo

2. What is NoSQL Database?

Before beginning NoSQL Database in Python, let’s find out about NoSQL.
NoSQL expands to “Not Only SQL”. It lends us a way to store and retrieve data that we can model in forms other than relational (tables). NoSQL databases largely find use in applications involving big data and real-time uses. The reason we call them “Not Only SQL” is because they may support query languages that are SQL-like. We can use NoSQL to store data in forms like key-value, document, columnar, and graph. When working with large sets of distributed data, we use NoSQL.
Do you How to Copy a File n Python Programming Language

3. Need for NoSQL Database in Python

So, why do we need NoSQL?

  • Instead of large monolithic servers and storage infrastructure, organizations now use cloud computing, open-source software, and commodity servers.
  • Projects now adopt agile approaches instead of long waterfall traditions (Agility).
  • There is a need to work with large volumes of data that changes type often. These types include unstructured, semi-structured, structured, and polymorphic data.
  • The size of audiences has grown exponentially over the years (Scalability).

4. Database Types with NoSQL

As we’ve discussed before, we have four different types of data we can model with NoSQL Database in Python-

How to Work with NoSQL Database in Python using PyMongo

How to Work with NoSQL Database in Python using PyMongo

a. Document Databases

In a document database, each key pairs with a document. A document is a complex data structure and can hold any of the following- key-value pairs, key-array pairs, nested documents. These store semi-structured data.
We use these for applications like content management and mobile application data handling.

b. Graph Stores

A graph store holds knowledge about data networks. One such network is social connections. In a graph store, a node is like a record in a relational database, and an edge is like a connection between nodes. This lets it represent data relationships better. We use these for applications like CRM and reservation systems. Some examples are Neo4J and Giraph.

c. Key-Value Stores

A key-value store holds key-value pairs in its structure. This is the simplest NoSQL database. We use these in applications like session management and caching in web applications. Some examples include Riak, Redis, and Berkeley DB.

d. Wide-Column Stores

When we want to store columns together working with queries over large datasets, we can use wide-column stores. We also find these in SQL databases and they query large volumes faster. Some examples are Cassandra, HBase, and Google BigTable.
Read About Python Forensics – Hash Function, Virtualization

5. Benefits of Using NoSQL Database

This are the following advantages of NoSQL Database in Python, let’s discuss them one by one:

  1. Easy and flexible object-oriented programming.
  2. Large volumes of rapidly changing data- unstructured, structured, or semi-structured.
  3. Scale-out architecture that is geographically distributed.
  4. Agile sprints, frequent code pushes, quick schema iteration.

6. NoSQL vs SQL

So, how are these two different? Let’s see.

  • Schemas are typically dynamic for NoSQL but fixed for SQL.
  • NoSQL can have different kinds of database, as discussed, but SQL has only one.
  • NoSQL came around in the late 2000s, SQL has been here since 1970s.
  • For SQL, the data storage model is individual records, but for NoSQL, this depends on the database type.
  • NoSQL has horizontal scaling; SQL has vertical.
  • For NoSQL, development is open-source; for SQL, it is a combination of open-source and closed-source.
  • The NoSQL DB used determines support for ACID transactions; SQL supports ACID transactions.
  • Examples of NoSQL databases are MongoDB, Cassandra, Neo4J, and HBase; Those for SQL databases are MySQL, Oracle, Microsoft SQL Server, and Postgres.

7. Installing the Prerequisites of NoSQL Database in Python

In this Python NoSQL Database tutorial, we use the library pymongo. It is the official driver published by Mongo developers. You can install it this way:
C:\Users\lifei>pip install pymongo
Collecting pymongo
Downloading https://files.pythonhosted.org/packages/0f/54/ec07858c625460027536aefe8bbe1d0f319b62b5884ec8650e1c2649dccb/pymongo-3.7.0-cp36-cp36m-win_amd64.whl (309kB)
100% |████████████████████████████████| 317kB 392kB/s
Installing collected packages: pymongo
Successfully installed pymongo-3.7.0
This installs version 3.7.0, which is the latest version of pymongo at the time of writing the tutorial.
You will also need to install the MongoDB database.
Follow this link to know more about MongoDB Database

8. Operations Perform in NoSQL Database in Python

How to Work with NoSQL Database in Python using PyMongo

How to Work with NoSQL Database in Python using PyMongo

a. Insert Operation

To insert data into a NoSQL database in Python 3, we use the insert() method. This is the code we use in the command prompt (You could also run a script or simply use the interpreter):

C:\Users\lifei>python

Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type “help”, “copyright”, “credits” or “license” for more information.

>>> from pymongo import MongoClient
>>> from pprint import pprint
>>> client=MongoClient() #Choose client
>>> db=client.test #Connect to DB
>>> student=db.student
>>> student_record={
... 'Name':'Ayushi Sharma',
... 'Enrolment':'0875CS191003',
... 'Age':'22'}
>>> result=student.insert_one(student_record)
>>> pprint(student.find_one({‘Age’:’22’}))

{u’Age’: u’22’,
u’Enrolment’: u’0875CS191003’,
u’Name’: u’Ayushi Sharma’,
u’_id’: ObjectId(‘7cyz7c2e72f5uh7829011e36’)}
Have a look The Best Article on Python’s Various Libraries

b. Update Operation

Now to update this data, we use the update() method.

>>> from pymongo import MongoClient
>>> from pprint import pprint
>>> client=MongoClient() #Choose client
>>> db=client.test #Connect to DB
>>> student=db.student
>>> db.student.update_one({'Age':'22'},
... {'$set': {'Name':'Ayushi Sharma',
.. 'Enrolment':'0875CS191003',
... 'Age':'23'}}) #Choosing the record to update
>>> pprint(student.find_one({‘Age’:’23’})

{u’Age’: u’23’,
u’Enrolment’: u’0875CS191003’,
u’Name’: u’Ayushi Sharma’,
u’_id’: ObjectId(‘7cyz7c2e72f5uh7829011e36’)}

c. Delete Operation

Now to delete this record, we can use the delete() method.

>>> from pymongo import MongoClient
>>> from pprint import pprint
>>> client=MongoClient() #Choose client
>>> db=client.test #Connect to DB
>>> student=db.student
>>> db.student.delete_one({‘Age’:’23’})
>>> pprint(student.find_one({‘Age’:’23’})

None
Here, Python prints None because it can’t find that record in the database.
So, this was all about NoSQL Database in Python. Hope you like our explanation.

9. Conclusion

Hence, this gets you started with the basics of using NoSQL databases in Python using PyMongo. Leave your queries in the comments below.
See Also- Python Career Opportunities
For reference

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

courses

DataFlair Team

DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.

Leave a Reply

Your email address will not be published. Required fields are marked *