0
0
MongoDBquery~30 mins

Single document atomicity in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Single Document Atomicity in MongoDB
📖 Scenario: You are managing a small online store's inventory using MongoDB. You want to update the stock quantity and price of a product in a way that both changes happen together or not at all, ensuring data consistency.
🎯 Goal: Build a MongoDB update operation that modifies multiple fields of a single product document atomically.
📋 What You'll Learn
Create a collection named products with one product document having fields _id, name, stock, and price.
Define a variable product_id holding the _id of the product to update.
Write an update query that atomically changes the stock and price fields of the product with _id equal to product_id.
Ensure the update uses a single document atomic operation.
💡 Why This Matters
🌍 Real World
In real online stores, updating product stock and price together prevents errors like selling out-of-stock items or showing wrong prices.
💼 Career
Understanding single document atomicity is essential for database developers and backend engineers to maintain data consistency and reliability.
Progress0 / 4 steps
1
Create the products collection with one product document
Create a products collection and insert one document with _id set to 1, name set to 'Wireless Mouse', stock set to 50, and price set to 25.99.
MongoDB
Need a hint?

Use insertOne to add a single document to the products collection.

2
Define the product_id variable
Define a variable called product_id and set it to 1 to represent the product's _id.
MongoDB
Need a hint?

Use const product_id = 1 to store the product's ID.

3
Write an atomic update query for the product document
Write an update query using updateOne on the products collection that finds the document with _id equal to product_id and atomically updates the stock to 45 and price to 23.99.
MongoDB
Need a hint?

Use updateOne with a filter on _id and the $set operator to update multiple fields atomically.

4
Complete the atomic update operation
Add the option {} to the updateOne method call to complete the update operation. This confirms the update is a single atomic operation on one document.
MongoDB
Need a hint?

Pass an empty options object {} as the third argument to updateOne to complete the call.