querydrill

Learn ›MongoDB fundamentals ›Updating arrays

The positional $ operator

arrayspositional $update$set

You have an array of objects and you want to change one of them, in place, without reading the document first. The positional $ is how - it stands for “the index the query filter matched”.

Given:

{
  _id: 101,

  orders: [
    {
      _id: 1011,
      product: "Laptop",
      status: "completed"
    },
    {
      _id: 1012,
      product: "Notebook",
      status: "pending"
    }
  ]
}

Update order 1012:

db.users.updateOne(
  {
    _id: 101,
    "orders._id": 1012
  },
  {
    $set: {
      "orders.$.status": "completed"
    }
  }
)

The $ here refers to the matched array element.

This is useful to remember.

There are also:

$        → first matching element

$[]      → all elements

$[x]     → filtered elements

Example:

db.users.updateOne(
  { _id: 101 },
  {
    $set: {
      "orders.$[].status": "archived"
    }
  }
)

Updates all array elements.

Practise this

1 exercise