Practical Update Examples
Real-World Scenarios for Nested Document Updates
graph TD
A[Update Scenarios] --> B[User Profile]
A --> C[E-commerce]
A --> D[Social Media]
A --> E[Logging Systems]
Example 1: User Profile Update
Initial Document Structure
{
"_id": ObjectId(),
"username": "johndoe",
"profile": {
"name": "John Doe",
"contact": {
"email": "[email protected]",
"phone": null
}
}
}
Update Phone Number
db.users.updateOne(
{ "username": "johndoe" },
{ $set: { "profile.contact.phone": "+1234567890" } }
)
Example 2: E-commerce Order Management
Nested Order Document
{
"_id": ObjectId(),
"orderNumber": "ORD-001",
"customer": {
"name": "Alice Smith",
"shipping": {
"address": "123 Main St",
"status": "pending"
}
}
}
Update Shipping Status
db.orders.updateOne(
{ "orderNumber": "ORD-001" },
{ $set: { "customer.shipping.status": "shipped" } }
)
Example 3: Adding Items to Nested Array
Document with Nested Array
{
"_id": ObjectId(),
"username": "developer",
"skills": {
"programming": ["Python", "JavaScript"],
"certifications": []
}
}
Add Certification
db.users.updateOne(
{ "username": "developer" },
{ $push: { "skills.certifications": "MongoDB Certified" } }
)
Complex Update Scenarios
Scenario |
Update Method |
Use Case |
Conditional Update |
$set with $filter |
Selective updates |
Atomic Updates |
findOneAndUpdate() |
Concurrent modifications |
Bulk Updates |
updateMany() |
Large-scale changes |
Advanced Update Techniques
- Upsert Option
- Multi-Document Updates
- Filtered Array Updates
Upsert Example
db.users.updateOne(
{ "username": "newuser" },
{ $set: { "profile": { "name": "New User" } } },
{ upsert: true }
)
- Use precise update operators
- Minimize document size changes
- Index nested document fields
- Validate input before updates
At LabEx, we emphasize understanding these practical update techniques to master MongoDB document management.