MongoDB Update Document
MongoDB provides multiple methods for updating documents, allowing you to update single or multiple documents.
Update Single Document
updateOne() Method
Basic Example
Return Result
Update Multiple Documents
updateMany() Method
Basic Example
Update Operators
$set - Set Field Value
$unset - Remove Field
$inc - Increment Value
$mul - Multiply Value
$rename - Rename Field
Array Operators
$push - Add Element to Array
$addToSet - Add to Set (No Duplicates)
$pop - Remove Array Element
$pull - Remove Specified Element
$pullAll - Remove All Specified Values
Replace Document
replaceOne() Method
Update Options
upsert - Insert if Not Exists
writeConcern
Bulk Update
Bulk Operations
Update Examples
Comprehensive Example
Summary
Key points for updating documents:
updateOne()for single document updatesupdateMany()for multiple document updatesreplaceOne()to replace entire document- Use various operators for different update needs
upsertcan "update if exists, insert if not"
In the next chapter, we will learn about MongoDB Delete Document.