Skip to content

CRUD

Array Update Operators

$push, $addToSet, $pop, $pull and $pullAll for changing arrays without replacing the whole document.

IntermediateAbout 6 minutes

Rahul's skills is an array. Do not $set the whole array unless you intend to replace it. These operators change membership. Matching a specific element by position ($, $[]) is a later lesson — here we add and remove.

db.users.updateOne(
  { email: "rahul@example.com" },
  { $push: { skills: "Express" } }
)
$push appends. Duplicates are allowed.
{ skills: ["Node.js", "MongoDB", "Express"] }
skills was ["Node.js", "MongoDB"]
db.users.updateOne(
  { email: "rahul@example.com" },
  { $addToSet: { skills: "MongoDB" } }
)
// skills unchanged — MongoDB was already present
$addToSet appends only if the value is not already there
db.users.updateOne(
  { email: "rahul@example.com" },
  { $pull: { skills: "Express" } }
)

db.users.updateOne(
  { email: "rahul@example.com" },
  { $pullAll: { skills: ["Express", "GraphQL"] } }
)

db.users.updateOne(
  { email: "rahul@example.com" },
  { $pop: { skills: 1 } }   // 1 = last element, -1 = first
)
Remove: $pull by value, $pullAll for a list, $pop for either end
  • `$push` — append. Use $each to append several: { $push: { skills: { $each: ["Redis", "SQL"] } } }.
  • `$addToSet` — set semantics for that value. Nested objects must match exactly to count as duplicates.
  • `$pull` — remove every equal value (or a condition). `$pullAll` — remove every value in a list.
  • `$pop`1 last, -1 first. Not 'pop index 3'.

Interview question

When do you use $push versus $addToSet?

Think about it first.