Updating and Deleting Documents
✏️ Updating and Deleting Documents
updateOne and updateMany
Both take a filter (which document(s) to change) and an update (what to change). updateOne affects only the first match; updateMany affects every matching document.
Update Operators: $set, $inc, $push
| Operator | Meaning |
|---|---|
$set | Set a field to a specific value (the most common update operator) |
$inc | Increment (or decrement, with a negative number) a numeric field |
$push | Append a value onto an array field |
$set — Change a Field
$inc — Adjust a Counter
$push — Append to an Array
Upserts: Update or Insert
Adding { upsert: true } as a third argument tells MongoDB: if no document matches the filter, insert a new one instead of doing nothing.
An Upsert for a Page-View Counter
Deleting Documents: deleteOne and deleteMany
Deleting
💻 Coding Challenges
Challenge 1: Update a Single Field
Write an updateOne call that sets a product named "Laptop"'s price field to 799.
Goal: Practice basic $set syntax.
Challenge 2: Append to an Array
Write an updateOne call adding a new tag "sale" to a product's tags array field, for the product named "Notebook".
Goal: Practice $push on an array field.
Challenge 3: Write an Upsert
Write an updateOne call that increments a visitor counter for a user identified by userId: "u42", creating the counter document with { userId: "u42", visits: 1 } if it doesn't exist yet.
Goal: Practice combining $inc with upsert: true.
If the second argument to updateOne has no operator like $set at all — just plain fields, e.g. db.users.updateOne({ name: "Alice" }, { email: "new@example.com" }) — MongoDB doesn't merge that field into the existing document. It treats the whole thing as a replacement document, wiping out every other field the original document had. This is exactly the REST PUT-vs-PATCH distinction from the API Types & Design course's HTTP chapter, applied to MongoDB: a bare update document behaves like a full PUT replacement, while wrapping it in $set behaves like a PATCH partial update. Always use $set (or another update operator) unless you genuinely intend to replace the entire document.
🎯 What's Next
The next chapter goes deeper into design itself: The Document Data Model & Schema Design — embedding vs. referencing, denormalization philosophy, and modeling one-to-many and many-to-many relationships as documents.