Node.js MongoDB Update
Here is a complete, easy, and practical guide for Node.js MongoDB Update operations.
✅ Node.js MongoDB Update
MongoDB provides two main update methods:
| Method | Description |
|---|---|
| updateOne() | Updates the first matching document |
| updateMany() | Updates all matching documents |
To update fields, MongoDB uses the $set operator.
⭐ 1. Update One Document
Set a new address where name = “John”
⭐ 2. Update Many Documents
Set the city = “Surat” for all customers from Gujarat
⭐ 3. Update Using Comparison Operators
Example: Increase age by 1 for all users age > 25
⭐ 4. Update Array Fields
Add a value to array ($push)
Remove from array ($pull)
⭐ 5. Update Nested Fields
Example document:
Update nested field:
⭐ 6. Replace Entire Document (replaceOne)
⚠ This replaces the whole document except _id.
⭐ 7. Upsert (Update or Insert)
If the document does not exist → insert it.
