Performing a MongoDB Update Using Set

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

One of the most common database operations developers and administrators need to know how to perform is the update operation. In an update, it’s possible to modify values in an existing document or replace a document in its entirety. This article will discuss the built-in MongoDB update set function, which allows users to modify a selected document within a collection by updating fields within the document or the entire document itself.

Prerequisite

Before proceeding with the examples in this tutorial, it’s important to confirm that MongoDB server is installed and configured on your machine.

MongoDB $set operator

The MongoDB $set operator can be used to replace a selected value of a field with a new set of value(s). If the field in question does not exist, it will be created with the given value.

The basic syntax for the $set operator is shown below:

1
{ $set: { <the_field>: <the_value1>, ... } }

NOTE: We use standard ‘dot notation’ to specify a field of an embedded document or within an array.

MongoDB $set Example

In this section, we’ll be looking at a few different examples that use the $set method.

Creating a sample database

Our first task will be to create a sample database that we’ll use for this tutorial. To do this, use the series of commands listed below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
> use hoteldb
switched to db hoteldb
> db.hotel.insertMany( [
...   { _id : "1001", name : "Hotel Pearl", location: "India", rating: [{by: "kelvin", rating: 4}] },
...   { _id : "1002", name : "Sofitel Philippines Plaza", location: "Manila", rating: [{by: "anton", rating: 5}] },
...   { _id : "1003", name : "Farimont Makati", location: "Makati", rating: [{by: "Donna", rating: 5}] },
...   { _id : "1004", name : "Four Season Resort Koh Samui", location: "Thailand", rating: [{by: "Kristin", rating: 5}] },
...  ] );
{
        "acknowledged" : true,
        "insertedIds" : [
                "1001",
                "1002",
                "1003",
                "1004"
        ]
}

To verify that our operation was successful, we can use the following command:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
> db.hotel.find().pretty()
{
        "_id" : "1001",
        "name" : "Hotel Pearl",
        "location" : "India",
        "rating" : [
                {
                        "by" : "kelvin",
                        "rating" : 4
                }
        ]
}
{
        "_id" : "1002",
        "name" : "Sofitel Philippines Plaza",
        "location" : "Manila",
        "rating" : [
                {
                        "by" : "anton",
                        "rating" : 5
                }
        ]
}
{
        "_id" : "1003",
        "name" : "Farimont Makati",
        "location" : "Makati",
        "rating" : [
                {
                        "by" : "Donna",
                        "rating" : 5
                }
        ]
}
{
        "_id" : "1004",
        "name" : "Four Season Resort Koh Samui",
        "location" : "Thailand",
        "rating" : [
                {
                        "by" : "Kristin",
                        "rating" : 5
                }
        ]
}
>

Update Top-Level Fields using $set

Now that we’ve created our database, we can try to perform a basic update on the top-level fields of our document. We’ll use the below command:

1
2
3
4
5
6
7
8
9
db.hotel.update(
   { _id: "1004" },
   { $set:
      {
        name: "The Beautiful Resort Koh Samui",
        rating: { by: "Mr. Kelvin", rating: 6 }
      }
   }
)

The output of this command will look like this:

1
2
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>

The result shown above tells us that one document matched the criteria and one was successfully modified. We can verify that the update was successful using the following command:

1
2
3
4
5
6
7
8
9
10
11
> db.hotel.find({_id: "1004"}).pretty()
{
        "_id" : "1004",
        "name" : "The Beautiful Resort Koh Samui",
        "location" : "Thailand",
        "rating" : {
                "by" : "Mr. Kelvin",
                "rating" : 6
        }
}
>

We can see that we were able to update the name field and the sub-document rating.

Update Sub-document Fields

In our next example, we’ll show you how to update a target field in a MongoDB sub-document. Let’s look at the command:

1
2
3
4
5
6
db.hotel.update(
   { _id: "1004" },
   { $set:
      {"rating.rating" : 5}
   }
)

The output should look like this:

1
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

To verify that our update was a success, we can run the same command as we did in the previous example:

1
2
3
4
5
6
7
8
9
10
> db.hotel.find({_id: "1004"}).pretty()
{
        "_id" : "1004",
        "name" : "The Beautiful Resort Koh Samui",
        "location" : "Thailand",
        "rating" : {
                "by" : "Mr. Kelvin",
                "rating" : 5
        }
}

We can see that we were able to update the field rating with a new value of ‘5’.

Conclusion

Being able to update documents is a key skill to have when you’re working with MongoDB as a developer or administrator. Using the update method in conjunction with $set allows you to modify fields in an existing document or replace the document itself. In this article, we showed you a few examples of how to use the MongoDB update set function. With these instructions and examples, you’ll be prepared to update documents in your own MongoDB collections.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.