Array Update Operators in MongoDB

From the MongoDB cheat sheet · Update Operators · verified Jul 2026

Array Update Operators

Modify array fields in documents

javascript
// Add to array
db.users.updateOne(
  { _id: userId },
  { 
    $push: { tags: "premium" },
    $addToSet: { hobbies: "reading" }  // No duplicates
  }
)

// Add multiple items
db.posts.updateOne(
  { _id: postId },
  { 
    $push: { 
      comments: { 
        $each: [comment1, comment2],
        $sort: { date: -1 },
        $slice: 10  // Keep only 10 newest
      }
    }
  }
)

// Remove from array
db.users.updateOne(
  { _id: userId },
  { 
    $pull: { tags: "old" },
    $pop: { history: -1 }  // Remove first (-1) or last (1)
  }
)
💡 $addToSet prevents duplicate values
📌 $ positional operator updates matched element
⚡ $push with $each for bulk array updates
⚠️ $pull removes ALL matching elements
🔗 Related: $pullAll, $pushAll (deprecated)
updateoperatorsarrays

More MongoDB tasks

Back to the full MongoDB cheat sheet