MongoDB Update Operations: 5 Quick Ways to Modify Documents

This article introduces 5 practical update operation methods for MongoDB, helping beginners quickly master the core skills of document modification: 1. **$set to Modify Fields**: Update or add fields while retaining other fields. Suitable for modifying partial fields (e.g., user email) or adding attributes. Syntax: `db.collection.updateOne({query}, {$set:{field: newValue}})`. 2. **$inc for Incrementing/Decrementing Values**: Increment or decrement numeric fields, used for counters, points, etc. Syntax: `db.collection.updateOne({query}, {$inc:{numericField: increment}})`, where increment can be positive or negative. 3. **$push for Array Appending**: Append elements to the end of an array while preserving the original array. Syntax: `db.collection.updateOne({query}, {$push:{arrayField: newElement}})`, automatically creates the array if it does not exist. 4. **replaceOne for Complete Replacement**: Replace a matched document with a new document, retaining only the `_id`. Syntax: `db.collection.replaceOne({query}, {newDocument})`; a new `_id` will be generated if the new document does not contain `_id`. 5. **updateMany for Bulk Updates**: Modify all documents that match the condition and return the number of matched/modified documents. Syntax: `db.collection.updateMany({query}, {updateOperation})` (Note: The original input was truncated; the full syntax should include the update operation, e.g., `{$set:{field: value}}`).

Read More