CRUD OperationsBeginner
1Question 1 of 1
javascriptHow do atomic update operators like $set, $inc, and $push work in MongoDB?
Explanation & Concept
MongoDB performs updates at the document level atomically. Rather than fetching, modifying in application memory, and saving the whole document (which risks lost updates from concurrent writes), you send atomic update operators directly to the database.
• `$set`: Overwrites specific fields without touching other keys. • `$inc`: Increments a numeric value atomically. • `$push`: Appends an element to an array. • `$pull`: Removes matching items from an array.
Code Example
javascript
db.products.updateOne(
{ _id: ObjectId("64f1a2b3c4d5e6f7a8b9c0d1"), stock: { $gte: 1 } },
{
$inc: { stock: -1, salesCount: 1 },
$push: { auditLog: { action: "SALE", timestamp: new Date() } },
$set: { lastModified: new Date() }
}
);How It Works & Key Takeaways
The query condition `{ stock: { $gte: 1 } }` acts as a guard. If another concurrent request already bought the last item, the query matches 0 documents and avoids negative inventory.
Mock Test · 1 Questions · Optional
Ready for Schema Design?
Take a quick test to evaluate yourself, or move straight to the next module.
Beginner1 questions