YouTip LogoYouTip

Mongodb Update

# MongoDB Update Documents In MongoDB, updating documents can be achieved using several methods depending on your requirements. The most commonly used methods are **`updateOne()`**, **`updateMany()`**, **`replaceOne()`**, and **`findOneAndUpdate()`**. This tutorial covers the syntax, parameters, and practical examples for each of these update operations. --- ## 1. updateOne() The `updateOne()` method updates a single document that matches the specified filter criteria. If multiple documents match the filter, only the **first** matching document will be updated. ### Syntax ```javascript db.collection.updateOne(filter, update, options) ``` ### Parameters * **`filter`**: The query criteria used to locate the document. * **`update`**: The update document or update operators (such as `$set`, `$inc`) to apply. * **`options`**: An optional object specifying additional configurations (e.g., `upsert`, `arrayFilters`). ### Example ```javascript db.myCollection.updateOne( { name: "Alice" }, // Filter criteria { $set: { age: 26 } }, // Update operation { upsert: false } // Optional parameters ); ``` --- ## 2. updateMany() The `updateMany()` method updates **all** documents that match the specified filter criteria. ### Syntax ```javascript db.collection.updateMany(filter, update, options) ``` ### Parameters * **`filter`**: The query criteria used to locate the documents. * **`update`**: The update document or update operators to apply. * **`options`**: An optional object specifying additional configurations (e.g., `upsert`, `arrayFilters`). ### Example ```javascript db.myCollection.updateMany( { age: { $lt: 30 } }, // Filter criteria { $set: { status: "active" } }, // Update operation { upsert: false } // Optional parameters ); ``` --- ## 3. replaceOne() The `replaceOne()` method replaces a single document matching the filter criteria with an entirely new document. Unlike `updateOne()`, which modifies specific fields, `replaceOne()` replaces the entire document (except for the immutable `_id` field). ### Syntax ```javascript db.collection.replaceOne(filter, replacement, options) ``` ### Parameters * **`filter`**: The query criteria used to locate the document. * **`replacement`**: The new document that will completely replace the old one. * **`options`**: An optional object specifying additional configurations (e.g., `upsert`). ### Example ```javascript db.myCollection.replaceOne( { name: "Bob" }, // Filter criteria { name: "Bob", age: 31 } // New replacement document ); ``` --- ## 4. findOneAndUpdate() The `findOneAndUpdate()` method finds a single document, updates it based on the specified criteria, and returns either the original document or the updated document. ### Syntax ```javascript db.collection.findOneAndUpdate(filter, update, options) ``` ### Parameters * **`filter`**: The query criteria used to locate the document. * **`update`**: The update document or update operators to apply. * **`options`**: An optional object specifying additional configurations (e.g., `projection`, `sort`, `upsert`, `returnDocument`). ### Example ```javascript db.myCollection.findOneAndUpdate( { name: "Charlie" }, // Filter criteria { $set: { age: 36 } }, // Update operation { returnDocument: "after" } // Optional: returns the updated document instead of the original ); ``` --- ## Common Options Parameters The `options` object across these update methods can include the following properties: | Option | Type | Description | | :--- | :--- | :--- | | **`upsert`** | Boolean | If set to `true`, creates a new document if no document matches the filter criteria. Defaults to `false`. | | **`arrayFilters`** | Array | An array of filter documents determining which array elements to modify when updating nested arrays. | | **`collation`** | Object | Specifies language-specific rules for string comparison (e.g., case-insensitive matching). | | **`returnDocument`** | String | Used in `findOneAndUpdate()`. Can be set to `"before"` (returns the document before update) or `"after"` (returns the document after update). | --- ## Quick Reference Examples ### Update a Single Document ```javascript db.myCollection.updateOne( { name: "Alice" }, { $set: { age: 26 } } ); ``` ### Update Multiple Documents ```javascript db.myCollection.updateMany( { age: { $lt: 30 } }, { $set: { status: "active" } } ); ``` ### Replace a Single Document ```javascript db.myCollection.replaceOne( { name: "Bob" }, { name: "Bob", age: 31 } ); ``` ### Find and Update a Single Document (Returning the Updated Version) ```javascript db.myCollection.findOneAndUpdate( { name: "Charlie" }, { $set: { age: 36 } }, { returnDocument: "after" } ); ``` --- ## Advanced Examples & Legacy `update()` Behavior > **Note:** In older versions of MongoDB, the `db.collection.update()` method was widely used. While modern drivers and shells recommend using `updateOne()`, `updateMany()`, or `replaceOne()` for clarity, understanding the legacy `update()` syntax is helpful when working with older codebases. The legacy `db.collection.update()` syntax is: ```javascript db.collection.update(filter, update, { upsert: , multi: }) ``` ### Legacy Example: Replacing or Saving a Document You can overwrite a document by saving a document with an existing `_id`: ```javascript db.col.save({ "_id" : ObjectId("56064f89ade2f21f36b03136"), "title" : "MongoDB", "description" : "MongoDB is a NoSQL database", "by" : "YouTip", "url" : "https://www.youtip.co", "tags" : [ "mongodb", "NoSQL" ], "likes" : 110 }) ``` Verify the saved document using `find().pretty()`: ```javascript > db.col.find().pretty() { "_id" : ObjectId("56064f89ade2f21f36b03136"), "title" : "MongoDB", "description" : "MongoDB is a NoSQL database", "by" : "YouTip", "url" : "https://www.youtip.co", "tags" : [ "mongodb", "NoSQL" ], "likes" : 110 } ``` ### Legacy `update()` Parameter Combinations #### 1. Update Only the First Matching Record By default, `update()` only modifies the first document it finds. ```javascript db.col.update( { "count" : { $gt : 1 } } , { $set : { "test2" : "OK"} } ); ``` #### 2. Update All Matching Records To update multiple documents using the legacy method, set the fourth parameter (`multi`) to `true`. ```javascript db.col.update( { "count" : { $gt : 3 } } , { $set : { "test2" : "OK"} }, false, true ); ``` #### 3. Upsert Only the First Record If no document matches, insert a new document (third parameter `upsert` set to `true`). ```javascript db.col.update( { "count" : { $gt : 4 } } , { $set : { "test5" : "OK"} }, true, false ); ``` #### 4. Upsert with Multi-Update Enabled ```javascript db.col.update( { "count" : { $gt : 5 } } , { $set : { "test5" : "OK"} }, true, true ); ``` #### 5. Increment Field Value for All Matching Records Use the `$inc` operator to increment numeric values. The following increments the `count` field by `1` for all documents where `count` is greater than `15`. ```javascript db.col.update( { "count" : { $gt : 15 } } , { $inc : { "count" : 1} }, false, true ); ``` #### 6. Increment Field Value for Only the First Matching Record ```javascript db.col.update( { "count" : { $gt : 10 } } , { $inc : { "count" : 1} }, false, false ); ```
← Mongodb RemoveMongodb Insert β†’