0PricingLogin
MongoDB Academy · Lesson

Updating Arrays: $push, $pull, $pop, $addToSet

Learners will atomically modify arrays inside documents using the full set of array update operators.

Array Update Operators Overview

MongoDB provides a rich set of array update operators that let you modify arrays inside documents atomically—without reading the document first, modifying it in application code, and writing it back. These operators are far more efficient and safe in concurrent environments than read-modify-write patterns. The main operators are: $push, $pull, $pop, and $addToSet.

Adding Elements With $push

$push appends one or more values to the end of an array. If the field does not exist, $push creates it as a new array containing the pushed value. $push allows duplicates—if you push the same value twice, it appears twice in the array. Use it when order and duplicates are acceptable, like append-only log arrays.

// Append a single tag
db.articles.updateOne(
  { _id: articleId },
  { $push: { tags: 'mongodb' } }
);

// Push creates the array if it doesn't exist
db.articles.updateOne(
  { _id: newId },
  { $push: { views: { date: new Date(), userId: 'u1' } } }
);
// If 'views' didn't exist, it's now [{ date: ..., userId: 'u1' }]

All lessons in this course

  1. Querying Arrays: $all, $size, and Element Match
  2. $elemMatch: Matching Array Sub-Documents
  3. Updating Arrays: $push, $pull, $pop, $addToSet
  4. Positional and Filtered Positional Updates
← Back to MongoDB Academy