Insert, Read, Update, Delete in MongoDB using PyMongo


Recently, I had the opportunity of working on Python web application with MongoDB as back end. In this PyMongo tutorial, I’ll brief about MongoDB Insert, Read, Update, Delete Using Python. I won’t be going into the details of how I installed MongoDB or any mongo shells commands like mongo show databases etc. I’ll stick to the part on how to interact with MongoDB using Python with help of the PyMongo connector.

Source code from this tutorial is available on GitHub.

Also read : RESTful API Authentication Using Python & AngularJS

Installing PyMongo, The Python MongoDb Connector

Assuming that you have python 2.7 already installed in your system, let’s start by installing PIP, the python package management system. Type in the following command to install pip :

sudo apt-get install python-pip

Once PIP has been installed, type in the following command to install PyMongo :

pip install pymongo

Now we are ready to connect to MongoDb using Python.

Connecting to MongoDb from Python

Let’s start by creating a file called crud.py. We’ll be creating this program as a command line program. So, we’ll display options to insert, edit, read and delete from command line.

Inside the file create a main python function where we’ll provide the option to read user input from command line. Here is how it would look like:

def main():

    while(1):
    # chossing option to do CRUD operations
        selection = raw_input('\nSelect 1 to insert, 2 to update, 3 to read, 4 to delete\n')
    
        if selection == '1':
            insert()
        elif selection == '2':
            update()
        elif selection == '3':
            read()
        elif selection == '4':
            delete()
        else:
            print '\n INVALID SELECTION \n'

PyMongo Tutorial : Insert Document to MongoDb

Define a python function called insert which would read the required data from user. Here is how it would look like:

# Function to insert data into mongo db
def insert():
    try:
        employeeId = raw_input('Enter Employee id :')
        employeeName = raw_input('Enter Name :')
        employeeAge = raw_input('Enter age :')
        employeeCountry = raw_input('Enter Country :')
    
    except Exception, e:
        print str(e)

The above code reads the required data from the user through the command line. Now, let’s make use of PyMongo to interact with MongoDb and insert a document. Import the MongoClient from PyMongo.

from pymongo import MongoClient

Create a client connection to the MongoDb instance running on the local machine using the following code:

client = MongoClient('localhost:27017')

Also define a database object to insert data into the MongoDb database.

# creating connectioons for communicating with Mongo DB
client = MongoClient('localhost:27017')
db = client.EmployeeData

Now that we have the database connection, let’s use the mongo db API to insert document to the database collection using the following command:

db.Employees.insert_one(
        {
        "id": employeeId,
            "name":employeeName,
        "age":employeeAge,
        "country":employeeCountry
        })

Here is the complete insert function :

# Function to insert data into mongo db
def insert():
    try:
        employeeId = raw_input('Enter Employee id :')
        employeeName = raw_input('Enter Name :')
        employeeAge = raw_input('Enter age :')
        employeeCountry = raw_input('Enter Country :')
        
        db.Employees.insert_one(
            {
                "id": employeeId,
                "name":employeeName,
                "age":employeeAge,
                "country":employeeCountry
        })
        print '\nInserted data successfully\n'
    
    except Exception, e:
        print str(e)

Try running the program and you should be able to insert a document into MongoDb.

PyMongo Tutorial : Read Document From MongoDb

Reading a document from MongoDb is too easier. All you have to do is call a find method on the collection and it would return all the documents in the collection. Here is the read function which would read all the documents and print it on the command line:

# function to read records from mongo db
def read():
    try:
        empCol = db.Employees.find()
        print '\n All data from EmployeeData Database \n'
        for emp in empCol:
            print emp

    except Exception, e:
        print str(e)

PyMongo Tutorial : Update Document From MongoDb

In order to update a document from the collection, we’ll set a criteria according to which we’ll update the collection. In this case, we’ll consider the employee id to update the document in the collection. So, add the update function as shown below to update the document :

# Function to update record to mongo db
def update():
    try:
        criteria = raw_input('\nEnter id to update\n')
        name = raw_input('\nEnter name to update\n')
        age = raw_input('\nEnter age to update\n')
        country = raw_input('\nEnter country to update\n')

        db.Employees.update_one(
            {"id": criteria},
            {
                "$set": {
                    "name":name,
                    "age":age,
                    "country":country
                }
            }
        )
        print "\nRecords updated successfully\n"    
    
    except Exception, e:
    print str(e)

In the above code, update_one api updates the one document with id and updates the fields defined in the $set.

PyMongo Tutorial : Delete Document From MongoDb

The code to remove a document from the collection is quite straight forward as the code to read the documents. We simply need to remove the document based on the employee id. So, here is the delete function to delete the employee based on the employee code.

# Function to delete record from mongo db
def delete():
    try:
        criteria = raw_input('\nEnter employee id to delete\n')
        db.Employees.delete_many({"id":criteria})
        print '\nDeletion successful\n' 
    except Exception, e:
        print str(e)

Wrapping It Up

In this tutorial, we saw how to do MongoDB Insert, Read, Update, Delete Using Python. It demonstrates how to implement the basic CRUD operation in MongoDb using Python. Hope you find the tutorial useful. Do let us know your thoughts in the comments below.

Also read : RESTful API Creation Using Python Flask & MySQL