Update MongoDB Document

In this post, we will learn to update a MongoDB Document. Update functionality is very important in every field so as in the MongoDB document. In MongoDB, we use the following two methods to update a MongoDB Document.

  • updateOne() and
  • updateMany()

updateOne() MongoDB document

The updateOne() method updates a single document that matches the filter criteria. The filter criteria is equivalent to the where clause in RDBMS like MySQL which matches the exact document so that it will update the correct document.

Syntax:

db.<collectionName>.updateOne(filterCriteria, update)

In the syntax above, we can see that updateOne() method accepts two different parameters. The first parameter is to match a document to be updated and the second parameter accepts the update query.

Let’s the original documents by executing the following query.

db.employee.find().pretty()

Output:

{
        "_id" : ObjectId("62f27f3587f66ea65f655524"),
        "name" : "Coder Sathi",
        "department" : "Engineering",
        "salary" : 50000,
        "address" : {
                "city" : "Kathmandu",
                "area" : "Pashupatinath"
        }
}
{
        "_id" : ObjectId("62f2806287f66ea65f655525"),
        "name" : "Radha Krishnan",
        "department" : "HR",
        "salary" : 50000,
        "address" : {
                "city" : "Pokhara",
                "area" : "Lakeside"
        }
}

We can see that, there are two documents in the employee collection.

Now, we found out that the employee whose name is Coder Sathi has an actual salary 60000 but in the document 50000 was inserted mistakely.

Our requirement is to update the salary of Coder Sathi to 60000.

First, make sure to find an employee whose name is Coder Sathi with the following query:

db.employee.find({"name": "Coder Sathi"}).pretty()

It returned the correct employee as an output:

{
        "_id" : ObjectId("62f27f3587f66ea65f655524"),
        "name" : "Coder Sathi",
        "department" : "Engineering",
        "salary" : 50000,
        "address" : {
                "city" : "Kathmandu",
                "area" : "Pashupatinath"
        }
}

Now, let’s execute an update query to change the salary of Coder Sathi.

The update query is:

db.employee.updateOne({"name": "Coder Sathi"}, {"$set":{ "salary": 60000}})

It showed the following output:

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

That basically means, one document is matched modified successfully.

Now, the time is to verify our data whether the update is success or not by executing the find query:

> db.employee.find({"name": "Coder Sathi"}).pretty()
{
        "_id" : ObjectId("62f27f3587f66ea65f655524"),
        "name" : "Coder Sathi",
        "department" : "Engineering",
        "salary" : 60000,
        "address" : {
                "city" : "Kathmandu",
                "area" : "Pashupatinath"
        }
}

Success!

Our document is modified as expected.

In this way, we can update a single document using updateOne() method.

updateMany() MongoDB documents

The updateMany() method updates more than one document that matches the filter criteria.

Syntax:

db.<collectionName>.updateMany(filterCriteria, update)

The updateMany() method also accepts the two different parameters same as updateOne() method and the use case is the same.

To understand it clearly, let’s take a simple example scenario so that it will be easier to understand.

Use case:

The management has decided to increase the salary of each employee by adding 5000. The decision was taken because the cost of living has also increased.

In this case, we have to execute a query so that it automatically increases the salary of all the employees that match the filter criteria.

Like we’ve used $set operator to set the value in updateOne() example earlier, we will use here $inc operator to increase the salary.

Example:

db.employee.updateMany({}, {"$inc":{ "salary": 5000}})

When we execute the above query we get the following output:


{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }

This basically means, it matched and modified the 2 documents. We already know that an employee collection has two documents.

Now verify whether the salary of each employee is increased by 5000 or not.

Use the db.employee.find().pretty() query and see the output as:

{
        "_id" : ObjectId("62f27f3587f66ea65f655524"),
        "name" : "Coder Sathi",
        "department" : "Engineering",
        "salary" : 65000,
        "address" : {
                "city" : "Kathmandu",
                "area" : "Pashupatinath"
        }
}
{
        "_id" : ObjectId("62f2806287f66ea65f655525"),
        "name" : "Radha Krishnan",
        "department" : "HR",
        "salary" : 55000,
        "address" : {
                "city" : "Pokhara",
                "area" : "Lakeside"
        }
}

Great!

We can see that the salary of employee is increased by 5000.

The first parameter filterCriteria is an optional parameter. If we don’t specify it then the updateMany method will update all the documents otherwise updates only to the matched document.

Update document with upsert

The upsert is an optional parameter that can be used while updating MongoDB documents.

This is a boolean type parameter so it accepts either true or false value and the default value for the upsert parameter is false.

When upsert is true then:

  • Either, it inserts a new document if no document matches the given query
  • Or updates an existing document that matches the given query.

See an example below:

Let’s assume that we have a single document in our employee collection. The document is given below:

{
        "_id" : ObjectId("62f77a41c41dfbf8c1e24e17"),
        "name" : "Coder Sathi",
        "department" : "Engineering",
        "salary" : 50000,
        "address" : {
                "city" : "Kathmandu",
                "area" : "Pashupatinath"
        }
}

Now, let’s execute an update query with the following command:

db.employee.updateOne({"name": "Radha Krishnan"}, {"$set":{ "salary": 60000}}, {"upsert": true})

What this query does is:

  1. It tries to find the existing document that matches the name as Radha Krishnan.
  2. Then it sets the value of the field salary to 60000.
  3. The upsert true will update the document by setting salary to 60000 if and only if the condition in item 1 satisfies otherwise it inserts the new document.

Now, see the output:

{
        "acknowledged" : true,
        "matchedCount" : 0,
        "modifiedCount" : 0,
        "upsertedId" : ObjectId("62f77d7616d0a350aca448c9")
}

This basically means that no document is matched and modified but the new document is updated with the upsertedId.


Because in our employee document, there is no document that matches the name as Radha Krishnan. Hence, the above query should insert a new document into our employee collection.

Let’s see if we have a new document in our collection.

Query:

db.employee.find().pretty()

And the output is:

{
        "_id" : ObjectId("62f77a41c41dfbf8c1e24e17"),
        "name" : "Coder Sathi",
        "department" : "Engineering",
        "salary" : 50000,
        "address" : {
                "city" : "Kathmandu",
                "area" : "Pashupatinath"
        }
}
{
        "_id" : ObjectId("62f77d7616d0a350aca448c9"),
        "name" : "Radha Krishnan",
        "salary" : 60000
}

We can see that the second document _id has the exact same value as upsertedId above.

Now, let’s execute the same updateOne() query without upsert or upsert false.

The query is:

db.employee.updateOne({"name": "Radha Krishnan"}, {"$set":{ "salary": 60000}}, {"upsert": false})

And the output is:

{ "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0 }

In our earlier example, we’ve seen the output with upsertedId when the upsert parameter in the update query was true but now it does not show here.

Hence, if the upsert is true and the given query didn’t match the document then the update command inserted a new document. But when it is false then id did nothing.

Summary

In this post, we learned to update MongoDB documents by using updateOne() and updateMany() method. Here, we learned to use $set and $inc operator. We also learned when to use upsert parameter while updating the MongoDB document.

There are multiple update operators in MongoDB you can take a look at the MongoDB documentation for Update Operators.

Sharing Is Caring:
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments