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" } }
){ skills: ["Node.js", "MongoDB", "Express"] }db.users.updateOne(
{ email: "rahul@example.com" },
{ $addToSet: { skills: "MongoDB" } }
)
// skills unchanged — MongoDB was already presentdb.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
)- `$push` — append. Use
$eachto 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` —
1last,-1first. Not 'pop index 3'.
Interview question
When do you use $push versus $addToSet?
Think about it first.
$push always appends, duplicates allowed. $addToSet appends only if that value is not already in the array. Skills, tags, roles — $addToSet. An event log where the same action can happen twice — $push.