0
0
MongoDBquery~5 mins

Single document atomicity in MongoDB

Choose your learning style9 modes available
Introduction

Single document atomicity means that when you change one document in MongoDB, the whole change happens all at once or not at all. This keeps your data safe and correct.

When updating a user's profile information in one go.
When adding an item to a shopping cart document.
When changing the status and timestamp in a single order document.
When incrementing a counter inside one document.
When replacing a whole document with new data.
Syntax
MongoDB
db.collection.updateOne(
  { filter },
  { update },
  { options }
)
The update affects only one document matching the filter.
The entire update is atomic on that single document.
Examples
Update the user with _id 1 to set their name to Alice.
MongoDB
db.users.updateOne(
  { _id: 1 },
  { $set: { name: "Alice" } }
)
Increase the quantity field by 2 in the order with orderId 123.
MongoDB
db.orders.updateOne(
  { orderId: 123 },
  { $inc: { quantity: 2 } }
)
Set price and stock fields atomically in the product with sku A100.
MongoDB
db.products.updateOne(
  { sku: "A100" },
  { $set: { price: 19.99, stock: 50 } }
)
Sample Program

This example shows inserting a cart document, then atomically adding a new item and increasing the total price in one update. Finally, it fetches the updated document.

MongoDB
use shopdb

// Insert a sample document
 db.carts.insertOne({ _id: 1, items: ["apple"], total: 5 })

// Atomically add an item and update total
 db.carts.updateOne(
   { _id: 1 },
   { $push: { items: "banana" }, $inc: { total: 3 } }
 )

// Find the updated document
 db.carts.findOne({ _id: 1 })
OutputSuccess
Important Notes

Single document atomicity works only within one document, not across multiple documents.

Use transactions if you need atomicity across multiple documents or collections.

Summary

MongoDB guarantees atomic updates on a single document.

All changes in one update happen fully or not at all.

This helps keep data consistent without extra effort.