Array Update Operators: $push, $pull, $addToSet
Learners will add and remove items from arrays inside documents using targeted array update operators.
Arrays as First-Class Citizens
Arrays inside MongoDB documents are common—a product has tags, a user has roles, an order has items. When these arrays need to change (add a tag, remove a role, append an order item), you need array update operators that modify the array in-place rather than replacing the entire document.
MongoDB provides a full set of operators for this purpose: $push adds elements, $pull removes elements by value, $pop removes from ends, and $addToSet adds only if unique. All of these are atomic—the change happens in a single server-side operation.
$push: Adding Elements to an Array
The $push operator appends one or more elements to an array field. If the field does not exist, $push creates it as a new array containing the pushed element. If the field exists but is not an array, the operation fails.
A single $push with a plain value adds one element. To add multiple elements in one operation, combine $push with the $each modifier. $push does not check for duplicates—use $addToSet if you need uniqueness.
// Push a single element
db.posts.updateOne(
{ _id: postId },
{ $push: { tags: 'mongodb' } }
);
// tags: ['node', 'backend'] -> ['node', 'backend', 'mongodb']
// Push multiple elements using $each
db.posts.updateOne(
{ _id: postId },
{ $push: { tags: { $each: ['databases', 'nosql'] } } }
);
// tags: ['node'] -> ['node', 'databases', 'nosql']
// Push a sub-document
db.users.updateOne(
{ _id: userId },
{ $push: { addresses: { street: '123 Main St', city: 'Chicago' } } }
);All lessons in this course
- updateOne and updateMany With $set and $unset
- Increment, Multiply, and Min/Max Operators
- Array Update Operators: $push, $pull, $addToSet
- Deleting Documents Safely With deleteOne and deleteMany