MongoDB Update Single / Multiple Documents in a Collection

Last updated on: by Digamber
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:

SeriesTutorial
1Install MongoDB on MacOS in 5 Minutes
2Install MongoDB on Windows
3MongoDB Create A Collection
4MongoDB Drop a Collection
5MongoDB Remove a Collection
6Uninstall 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>, ... ]
   }
)
ArgumentTypeDetials
querydocumentThe query parameter tells us which part of the document in a collection to be updated.
updatedocumentThe update parameter in MongoDB helps in deciding which modification has to be applied in a MongoDB document.
upsertbooleanThe 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.
multibooleanThe 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.
writeConcerndocumentThe writeConcern in mongoDB is an optional parameter, and this parameter is all about expressing the write concern of a document.
collationntThe 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

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.