Skip to content

Arrays & Nested Documents

Updating Arrays

Push, pull and addToSet in context, without repeating the operator catalogue from CRUD.

IntermediateAbout 5 minutes

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" } }
)
Skills: membership. Do not $set the whole array from a stale read.
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" } } }
)
Line items: $push a new row. $pull a row by a condition.

$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?

Think about it first.