Practical Update Examples
Real-World Scenarios for Array Modifications
1. User Skill Management System
graph LR
A[User Profile] --> B[Skills Array]
B --> C{Update Operations}
C -->|Add Skill| D[New Technology]
C -->|Remove Skill| E[Outdated Skill]
Code Example
## Initial user document
db.users.insertOne({
username: "techPro",
skills: ["Python", "JavaScript"]
})
## Add new skill
db.users.updateOne(
{ username: "techPro" },
{ $addToSet: { skills: "MongoDB" } }
)
## Remove outdated skill
db.users.updateOne(
{ username: "techPro" },
{ $pull: { skills: "JavaScript" } }
)
Operation |
MongoDB Operator |
Purpose |
Add Tags |
$push |
Expand product metadata |
Remove Specific Tag |
$pull |
Clean irrelevant tags |
Limit Tag Count |
$slice |
Maintain tag list size |
Comprehensive Example
db.products.updateOne(
{ productId: "laptop001" },
{
$push: {
tags: {
$each: ["gaming", "2023"],
$slice: -5 ## Keep only last 5 tags
}
}
}
)
3. Tracking User Activity Log
graph TD
A[User Activity] --> B[Append Log Entries]
B --> C{Maintain Log Size}
C --> D[Remove Oldest Entries]
Implementation
db.userActivity.updateOne(
{ userId: "user123" },
{
$push: {
activityLog: {
$each: [{ action: "login", timestamp: new Date() }],
$slice: -50 ## Keep last 50 activities
}
}
}
)
4. Advanced Conditional Updates
Unique Element Addition with Conditions
db.projects.updateOne(
{ projectId: "webApp" },
{
$addToSet: {
contributors: {
$each: ["alice", "bob"],
$position: 0 ## Insert at beginning
}
}
}
)
Best Practices
- Use
$addToSet
to prevent duplicates
- Leverage
$slice
for maintaining array size
- Combine multiple array operators in single update
LabEx Learning Strategy
LabEx recommends practicing these patterns through incremental complexity, starting with simple operations and progressing to more sophisticated array manipulations.
Error Handling and Validation
const result = db.collection.updateOne(
{ condition },
{ $push: { arrayField: newElement } }
)
if (result.modifiedCount === 0) {
print("Update failed or no matching document")
}
- Minimize full document replacements
- Use atomic array operators
- Index array fields for faster queries