Implementing $each Operations
Advanced $each Modifier Techniques
1. Basic Array Insertion
## Insert multiple tags for a blog post
db.posts.updateOne(
{ title: "MongoDB Tutorial" },
{
$push: {
tags: {
$each: ["database", "nosql", "tutorial"]
}
}
}
)
2. Combining $each with $slice
## Limit array size while adding new elements
db.logs.updateOne(
{ type: "system" },
{
$push: {
events: {
$each: ["error1", "error2", "error3"],
$slice: -5 ## Keep only the last 5 elements
}
}
}
)
3. Using $each with $sort
## Add elements and maintain sorted order
db.students.updateOne(
{ class: "LabEx-MongoDB" },
{
$push: {
scores: {
$each: [85, 90, 95],
$sort: 1 ## Sort in ascending order
}
}
}
)
Operation Types Comparison
Operation |
Description |
Use Case |
$push |
Adds elements to array |
Simple insertion |
$addToSet |
Adds unique elements |
Preventing duplicates |
$each |
Bulk array modification |
Complex array updates |
Advanced Workflow
graph TD
A[Initial Document] --> B[Select Update Target]
B --> C{Choose $each Modifier}
C -->|Basic Insertion| D[Add Multiple Elements]
C -->|Advanced| E[Apply Additional Modifiers]
E --> F[Slice/Sort/Position]
D --> G[Updated Document]
F --> G
4. Positional $each Operations
## Complex array manipulation
db.inventory.updateOne(
{ category: "electronics" },
{
$push: {
items: {
$each: [
{ name: "Laptop", price: 1000 },
{ name: "Smartphone", price: 500 }
],
$position: 2, ## Insert at specific index
$slice: 5 ## Limit total items
}
}
}
)
- Minimize the number of update operations
- Use $each for bulk modifications
- Leverage additional modifiers like $slice and $sort
- Consider document size limitations
Error Handling Strategies
## Check update result
const result = db.collection.updateOne(
{ filter },
{
$push: {
field: {
$each: elements
}
}
}
)
if (result.modifiedCount === 0) {
console.log("No documents were updated")
}
Common Pitfalls to Avoid
- Exceeding BSON document size limit
- Unnecessary repeated updates
- Ignoring performance implications
- Overlooking unique constraints
By mastering these $each implementation techniques, developers can efficiently manage complex array operations in MongoDB with LabEx-recommended best practices.