PyMongo Update Document

How PyMongo Update Document Works

In this quick tutorial you’ll learn how PyMongo update document works. PyMongo is a tool for interacting with MongoDB. From the official documentation,

PyMongo is a Python distribution containing tools for working with MongoDB, and is the recommended way to work with MongoDB from Python.

Getting Started With PyMongo

Make sure that you have Python installed in your distribution. If you are un sure, type in python in your terminal and if installed it will show the Python version installed.

# check if python installed
python --version

In my distribution it shows,

# python --version output
Python 2.7.14

You’ll be installing PyMongo tool using the Python package manager called pip.

# install python package manager
sudo apt-get install python-pip

Once pip has been installed, install PyMongo using pip.

# install pymongo using pip
pip install pymongo

How PyMongo Update Document Works

Let’s start by creating a connection to the MongoDB database using PyMongo. Create a file called app.py. Start by importing the MongoClient from PyMongo.

# import the PyMongoClient
from pymongo import MongoClient

You need to create a connection to MongoDB database running on your local system.

# create a connection
client = MongoClient('localhost:27017')

Once the connection to the MongoDB database has been established, you can make the calls to MongoDB database. Let’s first insert a record into the MongoDB database.

from pymongo import MongoClient

# create a mongo client
client = MongoClient('localhost:27017')

# select the database using the client
db = client.EmployeeData

# insert data into User collection
db.User.insert_one({
    "id": 1,
    "fname":'quasi',
    "lname":'meher',
    "country":'India'
})

The above code when executed will insert a document into the User collection in the EmployeeData database.

Now let’s update the fname of the User collection that you just inserted. For PyMongo update document to work you need to make use of the update_one method.

You’ll be updating the document based on the id of the user. Here is how it looks :

from pymongo import MongoClient

# create a mongo client
client = MongoClient('localhost:27017')

# select the collection using the client
db = client.EmployeeData

# update the collection document using update_one method
db.User.update_one(
    {"id": 1},
    {
        "$set": {
            "fname":"James",
            "lname":"Henderson"
        }
    }
)

Save the above changes and execute the python script. The MongoDb collection data will be updated as per the update script.

Wrapping It Up

In this PyMongo tutorial, you learnt how PyMongo update document works. For a detailed information on CRUD operations using PyMongo check out how to read, write and delete document using PyMongo.

Do let us know your thoughts and suggestions in the comments below.