Real-world Update Scenarios
E-commerce Product Management
Scenario: Dynamic Price and Stock Updates
## Connect to MongoDB
mongosh
## Switch to LabEx e-commerce database
use labex_ecommerce
## Insert sample product
db.products.insertOne({
name: "Machine Learning Course",
price: 99.99,
stock: 50,
discounts: []
})
## Update multiple fields simultaneously
db.products.updateOne(
{ name: "Machine Learning Course" },
{
$set: { price: 79.99 },
$inc: { stock: -10 },
$push: { discounts: "Summer2023" }
}
)
User Profile Management
Scenario: Incremental User Activity Tracking
## Create user activity collection
db.user_activities.insertOne({
username: "labex_developer",
total_courses: 3,
completed_labs: 25,
skill_tags: ["Python", "MongoDB"]
})
## Update user profile incrementally
db.user_activities.updateOne(
{ username: "labex_developer" },
{
$inc: { total_courses: 1, completed_labs: 5 },
$addToSet: { skill_tags: "Data Science" }
}
)
Update Scenarios Comparison
Scenario |
Update Operators |
Key Considerations |
Product Management |
$set , $inc , $push |
Real-time inventory tracking |
User Profile |
$inc , $addToSet |
Incremental skill development |
Subscription Service |
$currentDate , $max |
Automatic renewal management |
Complex Update Workflow
graph TD
A[Trigger Event] --> B{Update Type}
B --> |Price Change| C[Update Product Price]
B --> |Stock Adjustment| D[Modify Inventory]
B --> |User Progress| E[Track User Activities]
C,D,E --> F[Validate Update]
F --> G[Apply Changes]
G --> H[Log Transaction]
Advanced Update Strategies
Atomic Multi-document Updates
- Use transactions for complex updates
- Implement optimistic locking
- Ensure data consistency across collections
- Use selective field updates
- Minimize document size
- Leverage indexing for faster updates
Error Handling and Validation
## Example of update with validation
db.products.updateOne(
{
name: "Advanced MongoDB Course",
price: { $gt: 0 }
},
{
$set: { price: 129.99 },
$currentDate: { last_updated: true }
}
)
Best Practices for Real-world Updates
- Always validate input data
- Use appropriate update operators
- Implement comprehensive error handling
- Log critical update operations
- Monitor update performance
By understanding these real-world scenarios, developers can create robust and efficient MongoDB update strategies that adapt to complex application requirements.