How to update one or multiple documents in MongoDB

Updating database in MongoDB :

If you have one database, you need one method to update its data. MongoDB provides one really easy update method to update one single or multiple documents. You can also update only one value of a document. In this tutorial, I will show you two different examples to update one single or multiple documents using the update method. Note that this method works on the mongo shell. If you are using any other libraries in your project, the documentation may differ.

Syntax of update method :

The syntax of the update method is as below :

db.collection.update(query, update, {upsert, multi, writeConcern, collation, arrayFilters, hint})

Only the first two parameters are required. The other parameters are optional. You can refer to the official documentation to learn more.

Here, below two parameters are required :

query: Query to find the documents for an update. update: Modification to apply to the document.

Other parameters are optional.

If you set upsert is true, it will create one new document if no documents are found with the query. multi will update multiple documents if no documents are found.

Example 1: Find and update one document :

Steps :

> use Students
> db.Students.insert({"name": "Albert", "age": 20})
> db.Students.find()
> db.Students.update({"_id": ObjectId("5db42e61bdebce179ee055b6")},{$set: {"age": 21}})

Explanation :

  1. Create one new collection Students

  2. Add one new document to Students

  3. Check all documents in Students

  4. Update the age with a specific _id. The value of _id will be different on your laptop.

Similarly, you can update multiple values in that document.

MongoDB update one document

Example 2: Find and update multiple documents :

Let’s add one more document with the same name and different age and update the age of both documents using update :

> db.Students.insert({"name": "Albert", "age": 30})
> db.Students.find()
> db.Students.update({"name": "Albert"},{$set: {"age": 25}}, {multi: true})

MongoDB update multi document

Example 3: Add the document if it is not found using the query :

We can pass the optional value of upsert as true to add one new document if the query doesn’t find anything :

> db.Students.update({"name": "Bob"},{$set: {"age": 26}}, {upsert: true})

It will add one new document if no name Bob is found.

MongoDB update upsert document