Sikau

MongoDB · Day 4 · about 30 min

Updating and deleting

$set, $inc, $push, $pull, upserts and deletes.

Change just what changed

You rarely rewrite a whole document. Update operators change exactly the fields you name: set a price, add one to a counter, push a tag onto an array — atomically, even with many users at once.

updateOne, updateMany, deleteOne

printjson(db.dishes.updateOne({ name: "Momo" }, { $set: { price: 190 }, $push: { tags: "chef's pick" } }));

printjson(db.dishes.updateMany({ category: "drink" }, { $inc: { price: 10 } }));

db.dishes.updateOne({ name: "Sel roti" }, { $pull: { tags: "fried" }, $unset: { ratings: "" } });

printjson(db.dishes.updateOne({ name: "Lassi" }, { $set: { price: 90, veg: true, category: "drink" } }, { upsert: true }));

printjson(db.dishes.deleteMany({ price: { $gt: 250 } }));

printjson(db.dishes.find({}, { name: 1, price: 1, tags: 1, _id: 0 }).sort({ name: 1 }).toArray());
  • $addToSet adds to an array only if it isn't there already.
  • Without an operator, an update document is rejected — use replaceOne to replace a whole document.

The rest of this lesson

  • Atomic updates beat read-modify-writeexplain
  • Reading update resultsexplain
  • What happens?predict
  • Which operator?match
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of MongoDB