In this article, we will learn what MongoDB is, how to connect to the MongoDB database, and perform Insert, Read, Update, Delete in MongoDB using PyMongo with and Python.

What is MongoDB?

MongoDB is a company that runs a database called MongoDB. It’s an open-source document database that allows you to store large-scale data easily and you can work with your data very efficiently. MongoDB is a NoSQL database it means is not only a sequel database it can perform a lot more than that.

Why you should use MongoDB?

On the internet, there are lots of other databases like MongoDB ex. MySQL, JaguarDB, PostgreSQL, IBM Cloudant, and many more but why we are using MongoDB lets see:

  • MongoDB is a database that stores data in flexible form (JSON-like document).
  • JSON- like document model make it easy to mapping of the object application code, supports arrays, and allows for flexible and dynamic schemas.
  • Dynamic schemas mean you can store your data records with no worries of data structure such as the number of types of fields to store value.
  • MongoDB is a distributed database that supports horizontal scaling, and geographic distribution very easy to use.

Now that we know about the MongoDB database let’s see the process we need to do to connect to the MongoDB database and perform Insert, Read, Update, Delete in MongoDB using PyMongo.

What needs to be done?

  1. Installing the required tools for connecting to MongoDB.
  2. Importing the library – PyMongo.
  3. Connection to MongoDB database.
  4. Creating/inserting the document into the database collection.
  5. Reading the document that we stored in the database collection.
  6. Updating the document that we stored in the database collection.
  7. Deleting the document that we stored in the database collection.

Step -1: Installing the required tools for connecting to MongoDB

The required module tool we need is called PyMongo. It is a python based library that allows you to interact with the MongoDB database simply a driver for Python to use the MongoDB database. For performing Insert, Read, Update, Delete in MongoDB using PyMongo we need to install this library in our system for that you can simply copy-paste this common on your command prompt and should start installing.

pip3 install pymongo

Step -2: Importing the library – PyMongo

The first thing we are going to do is import PyMongo library which allows you to interact with the MongoDB database with its python native driver:

import pymongo  
from pymongo import MongoClient

Step -3: Connection to MongoDB database

In MongoDB, you can use cloud base database server or a local database in both case you need to create a server first for cloud base server you can go to this website and register.
And for local hosting, you can download and install the MongoDB community server from this website.

For establishing a local connection to the database we will need to set the host and port we intend to use and run on the local machine and we have to define the object insert into the MongoDB database.

HOST = 'localhost'
PORT = 27017
client = MongoClient(HOST, PORT)
database = client.cookbook
recipes = database.recipes

Now that we have the connection in the MongoDB database and the collection let’s do the Insert, Read, Update, Delete in MongoDB using PyMongo.

Step -4: Creating/inserting the document

For inserting the document named ‘recipe‘ into the database collection to perform Insert, Read, Update, Delete in MongoDB using PyMongo, we need to use MongoDB API to insert our document into our collection using insert_one():

recipe = {'title': 'chocolate milk',
          'description': 'Yummy drink',
          'ingredients': [
              {'name': 'milk', 'quantity': 8, 'unit of measure': 'ouncce'},
              {'name': 'chocolate syrup', 'quantity': 2, 'unit of measure': 'ouncce'}
          ],
          'yield': {'quantity': 1, 'unit': 'glass'},
          'prep time': 0,
          'cook time': 0,
          'author': 'Biff Tannen',
          'uploaded_by': 'kenwalger',
          }

recipes.insert_one(recipe)

Step -5: Reading the document

Reading the document in MongoDB is very easy. for that we have to do is simply use the function called find_one() function(find_one() is a collection level operator from PyMongo driver).as its name indicates it’s simply going to find the document we need in the collection and import the document, it’s very helpful if you only need to find the single document in the database. and we are going to add pprint so that our data should be print in a pretty fashion.

import pprint

print("\nPretty Printed document: \n")
pprint.pprint(recipes.find_one())

Output:



{'_id': ObjectId('588541a0146bde28a08217d4'),
 'author': 'Biff Tannen',
 'cook time': 0,
 'description': 'Yummy drink',
 'ingredients': [{'name': 'milk', 'quantity': 8, 'unit of measure': 'ounce'},
                 {'name': 'chocolate syrup',
                  'quantity': 2,
                  'unit of measure': 'ounce'}],
 'prep time': 0,
 'title': 'chocolate milk',
 'uploaded_by': 'kenwalger',
 'yield': {'quantity': 1, 'unit': 'glass'}}

Step -6: Updating the document

For updating the document from the database collection, we are going to set criteria in order to update our collection in a specific way here we are going to update the name of the author. for that, we need to use the update_one() method with the $set operator and printing the new data from the document stored in the database collection.

recipes.update_one({'title': 'chocolate milk'},
                   {'$set': {'author': 'George McFly'}
                    }
                   )
print("\nShould be George McFly: ")
pprint.pprint(recipes.find_one({'author': 'George McFly'}))

We are updating here the name of the author.

Output:

{'_id': ObjectId('588541a0146bde28a08217d4'),
 'author': 'George McFly',
 'cook time': 0,
 'description': 'Yummy drink',
 'ingredients': [{'name': 'milk', 'quantity': 8, 'unit of measure': 'ounce'},
                 {'name': 'chocolate syrup',
                  'quantity': 2,
                  'unit of measure': 'ounce'}],
 'prep time': 0,
 'title': 'chocolate milk',
 'uploaded_by': 'kenwalger',
 'yield': {'quantity': 1, 'unit': 'glass'}}

After you run the code you can see the difference as we updated the document it’s reflecting the name of the change from Biff Tannen to George McFly. Therefore, the process was a success and you can tell that it’s the same document because the ID number is the same as before.

Step -7: Deleting the document

The process of deleting the document is very simple just like reading the document. We simply need to use a method called delete_one(). We have to pass an argument for which document to delete. But our database collection has only one document in there for that reason we have a variety of select it, here we are going to utilize the unique identifier “_id” to ensure that we are only deleting the document we want in case there is lots of document in you database collection.

recipes.delete_one({'author': 'George McFly'})
print('Deleted the record:')
pprint.pprint(recipes.find_one())

Output:

Deleted the record:

This means our database collection is empty.

Final Words

In this article, we learn how to use the MongoDB database, how to install the PyMongo library, how to establish a connection to the MongoDB database, and how to Insert, Read, Update, Delete in MongoDB using PyMongo the document stored in the MongoDB database collection.

Let us know if you guys have any questions/comments regarding this process. Happy coding!

Here are some useful tutorials that you can read: