0
0
MongoDBquery~5 mins

Array update with positional $ operator in MongoDB

Choose your learning style9 modes available
Introduction

The positional $ operator helps you update a specific item inside an array in a document without changing the whole array.

You want to change the price of a specific product in a shopping cart array.
You need to update the status of a particular task inside a list of tasks.
You want to fix a typo in one comment inside an array of comments.
You want to mark one item as completed in a list of to-do items.
Syntax
MongoDB
db.collection.updateOne(
  { "arrayField.identifier": value },
  { $set: { "arrayField.$.fieldToUpdate": newValue } }
)

The query part finds the document with the array item matching the condition.

The $ in arrayField.$ means the first matched array element.

Examples
Updates the quantity of the first item with productId 123 in the items array.
MongoDB
db.orders.updateOne(
  { "items.productId": 123 },
  { $set: { "items.$.quantity": 5 } }
)
Marks the step with stepId 10 as done in the steps array.
MongoDB
db.tasks.updateOne(
  { "steps.stepId": 10 },
  { $set: { "steps.$.status": "done" } }
)
Changes the email address in the contacts array where type is email.
MongoDB
db.users.updateOne(
  { "contacts.type": "email" },
  { $set: { "contacts.$.value": "newemail@example.com" } }
)
Sample Program

This example inserts a document with an array of items. Then it updates the quantity of the item with sku 'def' to 50 using the positional $ operator.

MongoDB
db.inventory.insertOne({
  _id: 1,
  items: [
    { sku: "abc", qty: 10 },
    { sku: "def", qty: 20 },
    { sku: "xyz", qty: 30 }
  ]
})

print('Before update:')
printjson(db.inventory.findOne({_id: 1}))

// Update qty of item with sku 'def' to 50

const updateResult = db.inventory.updateOne(
  { "items.sku": "def" },
  { $set: { "items.$.qty": 50 } }
)

print('Update result:')
printjson(updateResult)

print('After update:')
printjson(db.inventory.findOne({_id: 1}))
OutputSuccess
Important Notes

The positional $ operator updates only the first matching array element.

If no array element matches, no update happens.

Use updateOne to update a single document, or updateMany to update multiple documents.

Summary

The positional $ operator lets you update one matching item inside an array.

You find the document and array element by a query, then use $set with arrayField.$.

This is useful to change just one part of an array without replacing the whole array.