Practical Coding Scenarios
Real-World Array Update Scenarios
1. User Profile Management
// Adding new skills to user profile
db.users.updateOne(
{ username: "johndoe" },
{
$addToSet: {
skills: {
$each: ["MongoDB", "Node.js"]
}
}
}
);
2. E-commerce Product Tagging
// Updating product categories dynamically
db.products.updateOne(
{ _id: productId },
{
$push: {
tags: {
$each: ["bestseller", "trending"],
$slice: -5 // Keep only last 5 tags
}
}
}
);
Scenario Complexity Levels
| Scenario |
Complexity |
Operator |
Use Case |
| Simple Append |
Low |
$push |
Adding single elements |
| Unique Insertion |
Medium |
$addToSet |
Preventing duplicates |
| Conditional Update |
High |
$push with modifiers |
Advanced filtering |
Mermaid Workflow Visualization
graph TD
A[Identify Update Requirement] --> B{Complexity Level}
B --> |Low| C[Simple $push]
B --> |Medium| D[Unique Insertion]
B --> |High| E[Advanced Modification]
C --> F[Execute Update]
D --> F
E --> F
// Moderating comments with array operations
db.posts.updateOne(
{ _id: postId },
{
$pull: {
comments: {
userId: moderatorId,
status: "inappropriate"
}
}
}
);
4. Inventory Tracking
// Managing product inventory locations
db.inventory.updateOne(
{ productCode: "ABC123" },
{
$push: {
warehouses: {
$each: [
{
name: "Central Warehouse",
quantity: 100
}
],
$position: 0 // Insert at beginning
}
}
}
);
Advanced Techniques
Conditional Array Modifications
// Update array based on complex conditions
db.users.updateMany(
{ age: { $gte: 18 } },
{
$addToSet: {
accessGroups: "adult_content"
}
}
);
Best Practices
- Use appropriate array update operators
- Consider performance implications
- Validate data before updates
- Implement proper error handling
Common Challenges
- Handling large arrays
- Maintaining data integrity
- Optimizing update performance
LabEx recommends practicing these scenarios to develop robust MongoDB array manipulation skills.