Modification Strategies
Document Modification Approaches
graph TD
A[Modification Strategies] --> B[Atomic Updates]
A --> C[Bulk Operations]
A --> D[Conditional Updates]
A --> E[Embedded Document Updates]
Atomic Updates
Ensuring Data Consistency
## Atomic increment with concurrent protection
db.inventory.updateOne(
{ _id: productId },
{
$inc: { quantity: -1 },
$set: { lastUpdated: new Date() }
}
)
Bulk Update Techniques
Strategy |
Method |
Use Case |
Ordered Bulk |
bulkWrite() |
Sequential updates |
Unordered Bulk |
bulkWrite() |
Parallel updates |
Bulk Update Example
const bulk = db.users.initializeUnorderedBulkOp();
bulk.find({ status: 'inactive' }).update({ $set: { status: 'archived' } });
bulk.find({ age: { $lt: 18 } }).update({ $set: { accessLevel: 'restricted' } });
bulk.execute();
Conditional Update Patterns
## Update only if condition is met
db.users.updateMany(
{
age: { $gte: 18 },
status: 'active'
},
{
$set: { membershipLevel: 'premium' }
}
)
Embedded Document Modifications
Updating Nested Structures
## Update specific array element
db.users.updateOne(
{ "contacts.type": "primary" },
{
$set: {
"contacts.$.verified": true,
"contacts.$.lastVerified": new Date()
}
}
)
Advanced Modification Strategies
Aggregation-Based Updates
db.users.aggregate([
{ $match: { status: 'active' } },
{ $set: {
scoreCategory: {
$switch: {
branches: [
{ case: { $gte: ['$score', 90] }, then: 'Excellent' },
{ case: { $gte: ['$score', 70] }, then: 'Good' }
],
default: 'Average'
}
}
}},
{ $merge: { into: 'users' } }
])
- Use targeted updates
- Minimize document size changes
- Create appropriate indexes
- Use
$set
for partial updates
Error Handling and Validation
const result = db.users.updateOne(
{ username: "labexuser" },
{ $set: { age: 30 } }
)
if (result.modifiedCount === 0) {
console.log("No documents were updated")
}
Best Practices
- Validate input before updates
- Use atomic operations
- Minimize write operations
- Handle potential race conditions
- Log significant modifications
Modification Workflow
graph LR
A[Identify Document] --> B[Validate Conditions]
B --> C[Prepare Update]
C --> D[Execute Update]
D --> E[Verify Result]
E --> F[Handle Errors]