Solution & Challenge: Update and Delete Operations · MongoDB
Ch 2 · MongoDB CRUD Operations — card 8 of 8.
Check your work against the worked solution, which lowers the laptop's price with $set, adds stock with $inc and removes items with zero or less in stock. The challenge is a shopping cart: add items with $push, change quantities using $set with dot notation, remove items with $pull, clear the cart with deleteOne, and cope with an empty cart.
await col.updateOne({ name: "Laptop" }, { $set: { price: 899 } });
await col.updateOne({ name: "Phone" }, { $inc: { stock: 10 } });
const del = await col.deleteMany({ stock: { $lte: 0 } });
console.log("Deleted:", del.deletedCount);- Use $push to add items
- Use $set with dot notation for nested updates
- Use $pull to remove items
- Handle empty cart