---
# System prepended metadata

title: MongoDB Update() Document- Scaler Topics

---

---
title: MongoDB Update() Document- Scaler Topics
description: This article by Scaler Topics explains different operations that can be done with the MongoDB update() Method with examples and explanations, read to know more.
Category: MongoDB
author: Srishti Gupta
---

:::section{.abstract}
## Overview

To update one or more documents in a collection we use MongoDB `Update()` method. The MongoDB `update()` method takes two arguments: the `<filter>` object that specifies which documents to update, and an `<update>` object that specifies the changes to make.

:::

:::section{.main}

## Introduction to MongoDB Update() Method 

Updating data is a fundamental operation in any database system, including MongoDB. In MongoDB, updating documents is done using the MongoDB `update()` method, which allows you to modify one or more documents that match specific criteria.

### Types of Updates

There are two types of updates you can perform in MongoDB: atomic updates and non-atomic updates.

**Atomic updates** are performed in a single operation and are considered to be more efficient and safer. MongoDB provides several atomic update operators, including `$set`, `$unset`, `$inc`, `$push`, `$pull`, `$addToSet`, and `$pop`.

**Non-atomic updates**, on the other hand, require multiple operations to complete and are inefficient and vulnerable. Examples of non-atomic updates include the `the findAndUpdate()` method which first finds a document and then modifies it separately, or using the `save()` method to completely replace a document.

### Syntax
The basic syntax of the Update() method is:

```css
db.collection.update(
   <filter>,
   <update>,
   <optional parameters>
)
```

### Parameters

**db.collection.update:** This is the basic command to update documents in a MongoDB collection.

* The `<filter>` parameter is a query document that specifies which documents to update. If the filter matches multiple documents, all matching documents will be updated unless the multi-option is set to false.

* `<update>`: This parameter specifies the update operation to perform. It can include one or more update operators, such as `$set`, `$unset`, `$inc`, `$push`, `$pull`, `$rename`, `$currentDate`, and many others. These operators are used to modify specific fields or values within the selected document(s). The third parameter is optional.

### Optional Parameters 

* **upsert:** This optional parameter specifies whether to insert a new document if no matching document is found. If set to true, MongoDB will insert a new document if no document matches the filtering criteria.

* **multi:** This optional parameter specifies whether to update multiple documents that match the filtering criteria. If set to true, MongoDB will update all matching documents; if set to false (the default), MongoDB will only update the first matching document.

* **writeConcern:** This optional parameter specifies the level of write concern for the update operation. It can be used to specify the number of replicas that must acknowledge the write before the operation is considered successful or to specify a timeout value.

:::

:::section{.main}

## Methods to Update Documents in MongoDB 

### Update Operators
MongoDB provides a variety of operators that can be used in the MongoDB `update()` method to modify documents in different ways. Some of the most commonly used operators include:

**$set:** Sets the value of a field in a document

**$unset:** Removes a field from a document

**$inc:** Increments the value of a numeric field in a document

**$push:** Adds an element to an array field in a document

**$pull:** Removes an element from an array field in a document

**$addToSet:** Adds an element to an array field only if it does not already exist in the array

**$pop:** Removes the first or last element from an array field in a document


### Update a Single Document

**update()**: This method by default updates only a single document that satisfies the filtering condition.
```css
db.collection.update(
   <filter>,
   <update>,
   {
      upsert: <boolean>,
      writeConcern: <document>
   }
)
```

**updateOne():** This method updates a single document that matches the specified filter.

```css
db.collection.updateOne(
   <filter>,
   <update>,
   {
      upsert: <boolean>,
      writeConcern: <document>
   }
)
```

### Update Multiple Documents
**update()**: When `multi` option is enabled then this method updates multiple documents that satisfy the filtering condition.

```css
db.collection.update(
   <filter>,
   <update>,
   {
      multi: true,
      upsert: <boolean>,
      writeConcern: <document>
   }
)
```

**updateMany():** This method updates all documents that match the specified filter.

```css
db.collection.updateMany(
   <filter>,
   <update>,
   {
      upsert: <boolean>,
      writeConcern: <document>
   }
)
```

### Replace a Document

**replaceOne():** This method replaces a single document that matches the specified filter with a new document.

```css
db.collection.replaceOne(
   <filter>,
   <replacement>,
   {
      upsert: <boolean>,
      writeConcern: <document>
   }
)
```

**findOneAndReplace():** This method finds a single document that matches the specified filter, replaces it with a new document, and returns the original document.

```css
db.collection.findOneAndReplace(
   <filter>,
   <replacement>,
   {
      projection: <document>,
      sort: <document>,
      maxTimeMS: <number>,
      returnNewDocument: <boolean>,
      upsert: <boolean>,
      writeConcern: <document>
   }
)
```

### Find and Update Behavior

Some optional parameters:

**sort:** specifies the order in which matching documents are processed

**projection:** a document that specifies which fields to return in the result document

**maxTimeMS:** It is used to specify the maximum amount of time that a query or command can run before being terminated by the server.

**returnNewDocument:** a boolean flag that indicates whether to return the modified document or the original document

**findOneAndUpdate():** This method finds a single document that matches the specified filter, updates it with the specified update operations, and returns the updated document.

```css
db.collection.findOneAndUpdate(
   <filter>,
   <update>,
   {
      projection: <document>,
      sort: <document>,
      maxTimeMS: <number>,
      returnNewDocument: <boolean>,
      upsert: <boolean>,
      writeConcern: <document>
   }
)
```

**findOneAndDelete():** This method finds a single document that matches the specified filter, deletes it and returns the original document.

```css
db.collection.findOneAndDelete(
   <filter>,
   {
      projection: <document>,
      sort: <document>,
      maxTimeMS: <number>,
      writeConcern: <document>
   }
)
```

:::

:::section{.main}
## Examples of MongoDB Update() Method

Certainly, here are some examples of how to use the  `update()` method in MongoDB:

**Basic Update:** To update a specific field in a document, you can use the `$set` operator as follows:

```css
db.collection.update(
   { _id: ObjectId("24") },
   { $set: { status: "inactive" } }
)
```

This will update the "status" field in the document with the specified `_id` to "inactive".


**Conditional Update:** To update a field only if a certain condition is met, you can use the `$inc` operator with the `$gt` operator as follows:

```css
db.collection.update(
   { _id: ObjectId("60c0b5d5c3c5f5b5e1e5c0e0"), 
       score: { $gt: 90 } },
   { $inc: { bonusPoints: 10 } }
)
```

This will add `10` bonus points to the document with the specified _id only if the "score" field is greater than `90`.

Update multiple documents where the score is greater than `90`;
```css
db.collection.update(
   { score: { $gt: 90 } },
   { $inc: { bonusPoints: 10 },
   {multi: true}}
)

// using updateMany
db.collection.updateMany(
   { score: { $gt: 90 } },
   { $inc: { bonusPoints: 10 }}
)
```

**Update with Aggregation Pipeline:** To update a document using an aggregation pipeline, you can use the `$addFields` operator as follows:

```css
db.collection.update(
   { _id: ObjectId("60c0b5d5c3c5f5b5e1e5c0e0") },
   [     { $addFields: { "newField": "some value" } }   ]
)
```

This will add a new field called "newField" with the value "some value" to the document with the specified `_id`.

:::

:::section{.faq-section}
## FAQs
**Q:** Can I update multiple documents in a single MongoDB update operation?

**A:** Yes, you can update multiple documents that match the filter criteria by setting the multi option to true in the update command.

**Q:** What is the difference between the \$set and \$unset operators in the MongoDB update?

**A:** The `$set` operator sets the value of a field in a document, while the `$unset` operator removes a field from a document.

**Q:** How can I update an array element in MongoDB?

**A:** You can update an array element in MongoDB using the $set operator with dot notation to specify the index of the element to update. For example, to update the third element in an array field named scores, you would use the field name `scores.2`.

**Q:** What is the purpose of the $addToSet operator in MongoDB update?

**A:** The $addToSet operator is used to add an element to an array only if the element is not already present in the array.

:::

:::section{.summary}
## Conclusion
* The MongoDB `update()` is used to modify one or more documents in a collection.
* It takes two arguments: a filter object that specifies which documents to update and an update object that specifies the changes to make.
* The update object can contain one or more update operators, such as `$set`, `$unset`, `$inc`, `$push`, `$pull`, and others.
* The upsert option is a boolean that determines whether to insert a new document if no matching documents are found.
* The multi-option is a boolean that determines whether to update all matching documents (true) or just the first one (false).
* The writeConcern option is a document that specifies the level of acknowledgment for the update operation.
* The `update()` method can still be used for backward compatibility with older versions of MongoDB.

Overall, the `update()` MongoDB method is a powerful tool for modifying data in MongoDB collections and provides a lot of flexibility with the use of update operators.

:::
