MongoDB Update If Condition

Introduction

The update is one of the CRUD operations provided by MongoDB. Whenever a database is created with collections and documents, it may require changes afterward. To make these changes, we use update operation. Further, sometimes we only want to update documents that match a certain condition. The update operation is one of the most commonly used CRUD operations in MongoDB that can accomplish this task. The syntax of the update operation is as follows.

The Update Command

db.collection.update(query,update,options)

The update operation has three parameters.

1.query

The first parameter is the query. It specifies the condition for the update operation. It is necessary to provide a query for the update operation to work properly.

2.update

The second parameter is the update itself. It specifies what are the changes we want to make in the document.

3.options

The third parameter is the various options provided by the update operation. This is optional. It consists of upsert, multi, writeconcern, collation, and array filters.

Demo How to Update If Meets Condition

The following database has one collection that consists of details of three members. Let’s have a look:

> db.details.find().pretty()
{
        "_id" : ObjectId("5d395f82eb75ca6e85cec7d2"),
        "name" : "John",
        "age" : 21,
        "city" : "New York"
}
{
        "_id" : ObjectId("5d395f86eb75ca6e85cec7d3"),
        "name" : "Peter",
        "age" : 22,
        "city" : "Texas"
}
{
        "_id" : ObjectId("5d395f8aeb75ca6e85cec7d4"),
        "name" : "Sam",
        "age" : 25,
        "city" : "Chicago"
}
>

Let’s see how to use the update operation. John is currently living in New York. But now he has moved to Texas. We can use update operation to change John’s city from New York to Texas.

> db.details.update({name:"John"},{$set : {"city": "Texas"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.details.find({name: "John"}).pretty()
{
        "_id" : ObjectId("5d39705beb75ca6e85cec7d5"),
        "name" : "John",
        "age" : 21,
        "city" : "Texas"
}
>

Observe the new result. John’s city is changed to Texas. Now have a look at the update operation. The first parameter is the query, {name: “John”}. This is the condition. The second parameter is the update we want. To change the city to Texas, a $set operator is used. This is how the update operation works with the condition.

Observe the result of the operation, the second line of the terminal above. In the second line, it says,{ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 }. “nMatched : 1” means the condition we used got a match worked and “nModified : 1” means, the update is completed. We will discuss “nUpsert” later.

We can also update multiple documents by using the update operation with the condition. We want to set the age of every person living in Texas to 30. This could be done by using the multi-option.

> db.details.update({city: "Texas"},{$set : {"age": 30}}, {multi:true})
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
> db.details.find().pretty()
{
        "_id" : ObjectId("5d39705beb75ca6e85cec7d5"),
        "name" : "John",
        "age" : 30,
        "city" : "Texas"
}
{
        "_id" : ObjectId("5d397061eb75ca6e85cec7d6"),
        "name" : "Peter",
        "age" : 30,
        "city" : "Texas"
}
{
        "_id" : ObjectId("5d397065eb75ca6e85cec7d7"),
        "name" : "Sam",
        "age" : 25,
        "city" : "Chicago"
}
>

We will use {city: “Texas”} as the condition. Then we will set the age as 30 for every record that matches the condition. But there are two people who live in Texas, John and Peter. We cannot use the normal update operation to update multiple documents. We can us multi option for this and set it to true. Observe the second line of the terminal. “nMatched” is 2 and “nModified” is also 2. This means, two documents were matched and those two were modified.

What if no document matches the conditions in the update operation? What happens then? Let’s see.

> db.details.update({name:"Lisa"},{$set : {"age": 30}})
WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })
>

Above, we tried to update the age of document where name is Lisa. Observe the second line of the terminal. It shows “nMatched” is 0. This means none of the document matched the query condition. No document with the name Lisa is present in the details collection. We can use the upsert option if there is no matching document. The upsert option will insert a new document if there is no match.

> db.details.update({name:"Lisa"},{$set : {"age": 30}}, {upsert:true})
WriteResult({
        "nMatched" : 0,
        "nUpserted" : 1,
        "nModified" : 0,
        "_id" : ObjectId("5d397683ca92454066f0acfb")
})

In the above update operation, We used upsert and set it to true. The result in the second line say “nMatched: 0” and “nModified :0”. There is no document where name is Lisa. But observe carefully, “nUpsert” is 1. This means a new document was added because there was no match. Lets have a look at the details collection once more.

> db.details.find().pretty()
{
        "_id" : ObjectId("5d3974c0eb75ca6e85cec7d8"),
        "name" : "John",
        "age" : 30,
        "city" : "Texas"
}
{
        "_id" : ObjectId("5d3974c9eb75ca6e85cec7d9"),
        "name" : "Peter",
        "age" : 30,
        "city" : "Texas"
}
{
        "_id" : ObjectId("5d3974ceeb75ca6e85cec7da"),
        "name" : "Sam",
        "age" : 25,
        "city" : "Chicago"
}
{
        "_id" : ObjectId("5d397683ca92454066f0acfb"),
        "name" : "Lisa",
        "age" : 30
}

We can see a new document was added with name as Lisa and age as 30. This is how upsert works.

Conclusion

The update operation is one of the most important parts of MongoDB’s CRUD operations. The condition is the query we pass as the first parameter of the update operation. As the second parameter, we pass the update itself. There are also various other options like multi and upsert that could be used with update operation. These options are passed as the third parameter. Although, the third parameter is optional.

We hope this tutorial on how to update based on a condition has helped you with your application. Thanks for joining us. If you have any database needs please don’t hesitate to reach out to us at Object Rocket.

Pilot the ObjectRocket platform free for 30 Days

It's easy to get started. Imagine the time you'll save by not worrying about database management. Let's do this!

PILOT FREE FOR 30 DAYS

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.