MongoDB Update Single or Multiple Documents in A Collection Tutorial

By Digamber Rawat Last updated on
In this MongoDB tutorial, we will learn to update single and multiple documents in a collection. MongoDB offers a wide array of methods to update a document in the collection if you are willing to update single or multiple documents at once, it’s pretty comfortable with the help of MongoDB.

MongoDB Tutorials For Beginners

If you are new to MongoDB, then check out below MongoDB tutorials. These tutorials will help you to get started with MongoDB:

Series Tutorial
1 Install MongoDB on MacOS in 5 Minutes
2 Install MongoDB on Windows
3 MongoDB Create A Collection
4 MongoDB Drop a Collection
5 MongoDB Remove a Collection
6 Uninstall MongoDB from Ubuntu

Update Method Syntax

Let’s get familiar with the MongoDB update() method’s syntax

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

The MongoDB update() method updates the current document in a collection. This method can update a particular part or an entire document in the collection. When we talk about its functionality, it updates the single document, but if you pass the multi-argument, then it will update all the documents.

Introduction to MongoDB Update Method Parameters

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ]
   }
)
Argument Type Detials
query document The query parameter tells us which part of the document in a collection to be updated.
update document The update parameter in MongoDB helps in deciding which modification has to be applied in a MongoDB document.
upsert boolean The mongoDB upsert is an optional parameter of update() method in MongoDB. If this parameter is set to true, It’ll create a new MongoDB document when the query doesn’t match in a document. It is set to false by default.
multi boolean The mongoDB multi is an optional parameter of MongoDB update() method. If this parameter is set to true, then It’ll update the multiple documents when meeting the query selection. The default value of this parameter is false. If this argument is set to false then it will update the single document.
writeConcern document The writeConcern in mongoDB is an optional parameter, and this parameter is all about expressing the write concern of a document.
collation nt The collation in mongoDB is an optional parameter, and this parameter allows users to define language-specific rules for making the string comparision.

For the detailed explanation visit MongoDB site here.

Accessing MongoDB Shell

To update document in MongoDB we are going to access the mongoDB shell using the following command:

mongo

Access your MongoDB database, in my case `angular8mean` is my my database.

> db
angular8mean
> use angular8mean
switched to db angular8mean

Create Collection using MongoDB Insert Method

We will update the MongoDB document but before that we must have a document if you already have document then you can skip this step otherwise enter the following command to insert the data into MongoDB document. By using the given command you’ll also be creating a new collection by the name of `employee`.

db.employee.insert(  
   {  
     name: "Elton John",  
     details: {  
        designation: "CEO", 
        Age: 34
     },
     department: "Marketing"  
   }  
)

Output for above command:

WriteResult({ "nInserted" : 1 })

Run command to see the employee collection with some data:

> db.employee.find().pretty()

{
        "_id" : ObjectId("5d0fcc43c572cf9d0f762c74"),
        "name" : "Elton John",
        "details" : {
                "designation" : "CEO",
                "Age" : 34
        },
        "department" : "Marketing"
}

MongoDB Update Single Document Example

Next, we are going to update a single data in MongoDB document using the update() method. In the example, we’ll update the name of the employee in the employee data object.

> db.employee.update({'name':'Elton John'},{$set:{'name':'Lil Wayne'}})

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

You can check out the updated document using the following command:

> db.employee.find().pretty()

{
        "_id" : ObjectId("5d0fcc43c572cf9d0f762c74"),
        "name" : "Lil Wayne",
        "details" : {
                "designation" : "CEO",
                "Age" : 34
        },
        "department" : "Marketing"
}

In the above example, we are using the $set value, this method is used to update the single or particular item in a document.

Update Document using MongoDB Upsert Parameter

In this example, we’ll see how does MongoDB upsert parameter work if set to true. The upsert parameter will check the matching _id if it doesn’t find the matching _id then it’ll create a new document.

db.employee.update({'name':'Lil Wayne'},{$set:{'name':'Justin B'}}, {upsert:true})

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

This will insert a new document, check out the below output of above query:

> db.employee.find().pretty()

{
        "_id" : ObjectId("5d0fcc43c572cf9d0f762c74"),
        "name" : "Justin B",
        "details" : {
                "designation" : "CEO",
                "Age" : 34
        },
        "department" : "Marketing"
}
{ "_id" : ObjectId("5d0fd1e800736b98aaaf8893"), "name" : "Lil Wayne" }

Update Multiple Documents using MongoDB Multi Parameter

In this example, we’ll see how to udpate multiple documents using the Multi parameter in MongoDB update method. if this parameter is set to true. Then the multi parameter update the multiple documents when meeting the query selection. By default it is set to false and when it is in false state then it updates only the single document in MongoDB. You can visit MongoDB site to know more about multi parameter.

db.employee.update({}, {$set: {"salary":500}}, {multi:true})

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

You can see the output below:

> db.employee.find().pretty()
{
        "_id" : ObjectId("5d0fcc43c572cf9d0f762c74"),
        "name" : "Justin B",
        "details" : {
                "designation" : "CEO",
                "Age" : 34
        },
        "department" : "HR",
        "salary" : 500
}
{
        "_id" : ObjectId("5d0fd1e800736b98aaaf8893"),
        "name" : "Lil Wayne",
        "department" : "HR",
        "salary" : 500
}

In the given above example, MongoDB multi parameter will update the entire document and set the 'salary' key along with '500' value.

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.