Update Document Matching
Understanding Document Update Matching
Document update matching in MongoDB involves selecting specific documents to modify based on precise criteria and update operators.
Update Operator Categories
graph TD
A[Update Operators] --> B[Field Update Operators]
A --> C[Array Update Operators]
A --> D[Conditional Update Operators]
Basic Update Matching Techniques
Field Update Operators
Operator |
Description |
Example |
$set |
Update specific fields |
{$set: {field: value}} |
$unset |
Remove specific fields |
{$unset: {field: ""}} |
$inc |
Increment numeric fields |
{$inc: {quantity: 1}} |
$rename |
Rename document fields |
{$rename: {oldName: newName}} |
Practical Update Example
## Connect to MongoDB
mongosh
## Use LabEx sample database
use employee_management
## Insert sample documents
db.employees.insertMany([
{ name: "Alice", department: "IT", salary: 5000 },
{ name: "Bob", department: "HR", salary: 4500 },
{ name: "Charlie", department: "IT", salary: 5500 }
])
## Update matching documents
db.employees.updateMany(
{ department: "IT" },
{ $inc: { salary: 500 } }
)
Conditional Update Strategies
Matching with Complex Conditions
## Update with multiple conditions
db.employees.updateOne(
{
department: "IT",
salary: { $lt: 5500 }
},
{
$set: { bonus: 1000 }
}
)
Advanced Update Matching
Array Update Techniques
graph LR
A[Array Update Methods] --> B[$push: Add Element]
A --> C[$pull: Remove Element]
A --> D[$addToSet: Unique Addition]
Array Update Example
## Update array fields
db.projects.updateOne(
{ name: "Web Development" },
{
$push: { team_members: "David" },
$addToSet: { skills: "React" }
}
)
Update Matching Best Practices
- Use precise matching criteria
- Leverage atomic updates
- Consider performance implications
- Validate update operations
Indexing for Updates
## Create index for faster updates
db.employees.createIndex({ department: 1, salary: 1 })
Upsert Operations
Conditional Insert or Update
## Upsert document if not exists
db.users.updateOne(
{ email: "[email protected]" },
{ $set: { status: "active" } },
{ upsert: true }
)
Error Handling and Validation
Update Matching Safeguards
- Use
$setOnInsert
for default values
- Implement schema validation
- Check update results
- Handle potential conflicts
LabEx Optimization Tips
- Monitor update performance
- Use bulk write operations
- Implement proper indexing
- Minimize document size
By mastering these update matching techniques, you'll efficiently manipulate MongoDB documents with precision and control.