How to Work with NoSQL Database in Python using PyMongo

How to Work with NoSQL Database in Python using PyMongo

What is NoSQL Database?

Before beginning the 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

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

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

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

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.

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.

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

Operations Perform in NoSQL Database in Python

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):

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

  1. >>> from pymongo import MongoClient
  2. >>> from pprint import pprint
  3. >>> client=MongoClient() #Choose client
  4. >>> db=client.test #Connect to DB
  5. >>> student=db.student
  6. >>> student_record={
  7. … ‘Name’:’Ayushi Sharma’,
  8. … ‘Enrolment’:’0875CS191003',
  9. … ‘Age’:’22'}
  10. >>> result=student.insert_one(student_record)
  11. >>> 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.

  1. >>> from pymongo import MongoClient
  2. >>> from pprint import pprint
  3. >>> client=MongoClient() #Choose client
  4. >>> db=client.test #Connect to DB
  5. >>> student=db.student
  6. >>> db.student.update_one({‘Age’:’22'},
  7. … {‘$set’: {‘Name’:’Ayushi Sharma’,
  8. .. ‘Enrolment’:’0875CS191003',
  9. … ‘Age’:’23'}}) #Choosing the record to update
  10. >>> 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.

  1. >>> from pymongo import MongoClient
  2. >>> from pprint import pprint
  3. >>> client=MongoClient() #Choose client
  4. >>> db=client.test #Connect to DB
  5. >>> student=db.student
  6. >>> db.student.delete_one({‘Age’:’23’})
  7. >>> 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.

Conclusion

Hence, this gets you started with the basics of using NoSQL databases in Python using PyMongo. Leave your queries in the comments below.