juniorMongoDB
How do you update a document in MongoDB?
Updated May 1, 2026
Short answer
Use updateOne(), updateMany(), or replaceOne() with operators like $set.
Deep explanation
The $set operator updates specific fields without overwriting the entire document, which is critical for maintaining atomicity.
Real-world example
Changing a user's password or email address.
Common mistakes
- Forgetting $set and overwriting the whole document with a partial object.
Follow-up questions
- What does upsert: true do?