Lesson 16 +10 XP

Array Update Operators

Array Update Operators

When a document field is an array, MongoDB has dedicated operators to modify it.

The array operators

OperatorMeaning
$pushAdds an element to an array
$pullRemoves all elements matching a value
$popRemoves the first or last element
$addToSetAdds an element only if it's not already there

Using them

// Add "sports" to the tags array
db.posts.updateOne({ title: "Post Title 1" }, { $push: { tags: "sports" } })

// Remove all "events" from tags
db.posts.updateMany({}, { $pull: { tags: "events" } })

// Remove the last element of the tags array
db.posts.updateMany({}, { $pop: { tags: 1 } })

// Add "news" only if it isn't already in tags
db.posts.updateOne({ title: "Post Title 1" }, { $addToSet: { tags: "news" } })

$push vs $addToSet

  • $push always adds the element, even if a duplicate already exists.
  • $addToSet only adds it if it's not already there (set behavior, no duplicates).

$pop direction

{ $pop: { tags: 1 } } removes the last element; { $pop: { tags: -1 } } removes the first.

TL;DR

  • $push appends an element; $addToSet appends only if new.
  • $pull removes matching elements; $pop removes first or last.