Python NoSQL DataBase

We offer you a brighter future with FREE online courses - Start Now!!

We all deal with data and we need a way to store, modify and access it. We all would have been familiar with SQL, one of the popular database management systems. In addition, we have NoSQL, which is also a database management system.

In this article, we will be discussing the NoSQL database and also its implementation using the Python pymongo module. Let us start with the introduction to NoSQL.

What is NoSQL?

NoSQL is a database system that allows us to store and handle the data in formats other than traditional tabular structures. It stands for “Not Only SQL” showing that they may also support query languages like SQL. It is widely used in applications involving big data and real-time uses. With the increase in unstructured or semi-structured data, the use of NoSQL databases is increasing. It lets us store the data in the form of key-value, document, columnar, and graph.

Different database types in NoSQL

There are four different types of data that we can model using NoSQL and these include:

1. Document Databases

In this database, a key is used to pair with a document. A document stores sem structured data which can be key-value pair, key-array pair, and/or nested documents.
It is used in applications like content management and handling data in mobile applications.

2. Graph Stores

It is a database used to store information about data networks. When we think of a network, we obviously remember social media. Yes! It is used for managing social media connections. In this, a node acts like a record in a relational database, and an edge acts as a link between the nodes. It is used for CRM and reservation systems like Neo4J and Giraph.

3. Key-Value Stores

In this type of database, the information is stored in the form of key-value pairs. Remembering dictionaries? Yes, the data looks like a dictionary! This is the simplest NoSQL database. It is used in applications like session management and caching in web applications. Some of them include Riak and Berkeley DB.

4. Wide-Column Stores

This is used to store columns like data over large datasets, we can use wide-column stores. These are also found in SQL databases. Some applications include Cassandra, HBase, and Google BigTable.

Why NoSQL?

You would have got some understanding by now of what applications NoSQL is used for. Let us see some more reasons why it is opted.

1. It is easy and flexible object-oriented programming.

2. It can be used to handle large volumes of data either unstructured, structured, semi-structured, or polymorphic.

3. It provides agile sprints, frequent code pushes, and quick schema iteration. And projects now adopt agile approaches instead of long waterfall traditions.

4. It also has architecture that is geographically distributed and the size of audiences has grown exponentially over the years.

Difference between SQL and NoSQL

Now let us also see how different NoSQL is from SQL.

1. SQL was released in the 1970s and NoSQL was released later in the 2000s.

2. For SQL the schemas are static whereas they are dynamic for NoSQL.

3. There are different kinds for data type models in NoSQL whereas SQL has only one.

4. NoSQL has horizontal scaling and SQL has vertical scaling.

5. Development of NoSQL open-source but it is a combination of open-source and closed-source for SQL.

6. Some applications of NoSQL databases include MongoDB, Cassandra, Neo4J, and HBase and those for SQL are MySQL, Oracle, Microsoft SQL Server, and Postgres.

Installation of Pymongo library

We are starting the implementation part of the NoSQL database. Before using the respective library, we need to install it. We can install it by writing the below command.

pip install pymongo

Output:

Collecting pymongo
Downloading pymongo-3.12.0-cp38-cp38-win_amd64.whl (397 kB)
|████████████████████████████████| 397 kB 930 kB/s
Installing collected packages: pymongo
Successfully installed pymongo-3.12.0

Next, we will see the insert, update, and delete operations on the NoSQL database using the pymongo library.

Insert Operations in MongoDB

To insert data into MongoDB in Python, we use the insert() method. This is the method available in the above installed library. Let us take an example and discuss it.

Example of insert operation in MongoDB:

# Import the required Python libraries
from pymongo import MongoClient
from pprint import pprint

client = MongoClient() # Choose the client

db=client.test # Connect to the chosen db 

student = db.student # Use the student collection in the database

#creating a details of the student in key-value pairs and storing it in a variable
stdt_info = {
    'Name': 'ABC',
    'Class': '5',
    'Roll_No': '12',
    'Age': '11'
}

result = student.insert_one(stdt_info) # Inserting the data using the insert method

output = student.find_one({'Roll_No': '12'}) # Query to find the inserted information.
pprint(output) #printing the output

Output:

{u’Age’: u’11’,
u’Class’: u’5′,
u’Name’: u’ABC’,
u’Roll_No’: u’12’
u’_id’: ObjectId(‘6coe7c0k34h5ao3829221o48’)}

In this example,

1. We first imported the required modules pymongo and pprint. We are using pprint module here so that when we try to print the information of the student we get the output in more readable form (i.e., in different lines).
2. Next, we instantiated the MongoClient() class
3. Then we choose the database created in mongodb and also test the connection
4. Then we use the student collection in the database
5. After this, we create the information of the student and insert it using the function.
6. Then we see the result by getting it using the find_one() function and giving one of the key-value pairs as the argument.

Update Operation

To update the data using MongoDB, we use the update() method. This is similar to the insert() operation, except that we use a different method. We will discuss using the above example and modifying the inserted data.

Example of update operation in MongoDB:

# Import the required Python libraries
from pymongo import MongoClient
from pprint import pprint

client = MongoClient() # Choose the client

db=client.test # Connect to the chosen db 

student = db.student # Use the student collection in the database

#updating the details of the student 
db.student .update_one(
        {'Roll_No':'12'},
        {
        "$set": {
            'Name': 'ABC',
            'Class': '5',
            'Roll_No': '12',
            'Age': '12'

        }
        }
    )

output = student.find_one({'Roll_No': '12'}) # Query to find the updated information.
pprint(output) #printing the output

Output:

{u’Age’: u’12’,
u’Class’: u’5′,
u’Name’: u’ABC’,
u’Roll_No’: u’12’
u’_id’: ObjectId(‘6coe7c0k34h5ao3829221o48’)}

Delete Operation

Similar to the above two methods, we use the delete() method to delete the data in the database. Let us see an example to delete the inserted data and see what we get as output after deleting.

Example of delete operation in MongoDB:

# Import the required Python libraries
from pymongo import MongoClient
from pprint import pprint

client = MongoClient() # Choose the client

db=client.test # Connect to the chosen db 

student = db.student # Use the student collection in the database

#deleting the details of the student 
db.employee.delete_one({'Roll_No': '12'})

output = student.find_one({'Roll_No': '12'}) # Query to find the information.
pprint(output) #printing the output

Output:

None

Conclusion

In this article, we learned about NoSQL, its data types, its benefits, and its differences from SQL. Then we saw the implementation of different operations using the pymongo library.

Hope you enjoyed reading the article and understood the concepts. Happy learning!

Did you like our efforts? If Yes, please give PythonGeeks 5 Stars on Google | Facebook

Leave a Reply

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