Arrays & Nested Documents
Updating Arrays
Push, pull and addToSet in context, without repeating the operator catalogue from CRUD.
CRUD already covered $push, $addToSet, $pull, $pullAll, $pop. This is when to use them on real shapes — skills vs line items — not another operator list.
db.users.updateOne(
{ email: "rahul@example.com" },
{ $addToSet: { skills: "Express" } }
)db.orders.updateOne(
{ _id: ObjectId("64a1b2c3d4e5f6a7b8c90011") },
{
$push: {
items: { name: "USB-C Cable", quantity: 1, unitPrice: 200 }
}
}
)
db.orders.updateOne(
{ _id: ObjectId("64a1b2c3d4e5f6a7b8c90011") },
{ $pull: { items: { name: "USB-C Cable" } } }
)$pull with an object removes elements that match that query, not only exact whole-element equality. { name: "USB-C Cable" } pulls every item with that name, whatever quantity is. $addToSet on an object only skips a duplicate if the entire object is equal — two cables with different quantities are both kept.
- Replace the array (
$set: { items: [...] }) when the client sends the full new list and you accept last-write-wins. - Patch membership when two requests might add skills or items at once —
$addToSet/$push/$pull. - Change a field on one item (quantity++, price) is not pull-and-push. That is positional operators, next.
Interview question
How do you remove one object from an array of documents?
$pull with a condition, e.g. { $pull: { items: { name: "USB-C Cable" } } }. That removes every element that matches, not only an exact deep-equal object. To change a field on a remaining element, use a positional operator instead of pull-and-push.