Updating and Deleting

Change documents without replacing them: set and unset fields, count up ratings, add to and remove from lists, insert-or-update with an upsert, and delete documents with a check first, so nothing you meant to keep disappears.

Updated

Updating Documents

  1. Changing Documents with updateOne and $set (Apprentice): updateOne and updateMany change documents where they are, with a filter that picks the documents and an update operator that says what changes; $set writes fields, $unset removes them, and matchedCount and modifiedCount report what happened.
  2. More Update Operators: $inc, $push, $pull and $addToSet (Apprentice): $inc lets the database do the counting so no count is lost, $currentDate stamps when a change happened, $push and $pull add to and remove from a list, and $addToSet adds an item only when it isn't there yet.
  3. Upserts and Replacing a Whole Document (Journeyman): An upsert updates a document when the filter finds one and inserts it when it doesn't, $setOnInsert sets values only on that first insert, replaceOne swaps in a whole new version, and findOneAndUpdate changes a document and hands it back.

Deleting Documents

  1. Deleting Documents Safely (Apprentice): deleteOne and deleteMany remove the documents a filter matches, with no undo, so you run the same filter with find first; an empty filter deletes everything, drop removes the whole collection, and a soft delete hides a document without losing it.

Exercise: Ratings and Favorites

  1. Exercise: Ratings and Favorites (Apprentice): Write seven mongosh changes behind Sunday Kitchen's buttons, from rating a recipe and counting its saves to saving a meal plan with an upsert and deleting old plans, and let the tests check every document afterward.

Up Next: Modeling

  1. Up Next: Modeling (Apprentice): Look back at the queries and changes you can write after Module 2, see them work together behind a recipe search page, and get a first look at Module 3, where you decide the shape of the documents for a whole online store.