Update Filtering Methods
Overview of MongoDB Update Filtering
MongoDB provides multiple methods to filter and update documents, each with unique characteristics and use cases.
Primary Update Methods
1. updateOne()
Updates a single document matching the filter criteria.
db.users.updateOne(
{username: "johndoe"},
{$set: {status: "active"}}
)
2. updateMany()
Updates multiple documents matching the filter conditions.
db.products.updateMany(
{category: "electronics", price: {$lt: 100}},
{$inc: {quantity: -5}}
)
Advanced Filtering Techniques
graph TD
A[Update Filtering] --> B[Comparison Operators]
A --> C[Logical Operators]
A --> D[Array Operators]
Filtering Operators for Updates
Operator |
Description |
Example |
$set |
Replace field value |
{$set: {age: 30}} |
$inc |
Increment numeric value |
{$inc: {score: 5}} |
$push |
Add element to array |
{$push: {tags: "new"}} |
$pull |
Remove array elements |
{$pull: {tags: "old"}} |
Complex Filter Examples
## Update with multiple conditions
db.employees.updateMany(
{
department: "sales",
salary: {$lt: 50000},
status: "active"
},
{$inc: {salary: 2000}}
)
LabEx Pro Tip
Mastering update filtering requires understanding both filter conditions and update operators.
Best Practices
- Always use precise filters
- Test update operations in a safe environment
- Use projection to limit updated fields
- Consider performance implications of complex updates