Update and Delete Operations in Code · MongoDB
Ch 2 · MongoDB CRUD Operations — card 6 of 8.
This example carries on with the three posts from Card 2.2 and changes them one at a time and in bulk. See how a single updateOne call combines $set and $inc, and how updateMany labels every post with fewer than 10 likes, which is only Post 3. Then deleteOne removes Post 2 by title and deleteMany clears the labelled post. Check deletedCount in each result, which tells you how many documents actually went.
// Starting data: the three posts from Card 2.2
// Post 1 (10 likes), Post 2 (25 likes), Post 3 (5 likes)
// Update operations
await collection.updateOne(
{ title: "Post 1" },
{ $set: { likes: 15 }, $inc: { views: 1 } } // views did not exist, so $inc creates it as 1
);
await collection.updateMany(
{ likes: { $lt: 10 } },
{ $set: { status: "low-engagement" } } // only Post 3 matches
);
// Delete operations
const one = await collection.deleteOne({ title: "Post 2" });
console.log("deleteOne removed:", one.deletedCount); // 1
const many = await collection.deleteMany({ status: "low-engagement" });
console.log("deleteMany removed:", many.deletedCount); // 1 (Post 3)- Forgetting the $ operator in updates
- Using updateOne when updateMany is needed
- Accidentally deleting all documents with empty filter