0
0
MongoDBquery~5 mins

Array update with $[identifier] filtered in MongoDB

Choose your learning style9 modes available
Introduction

We use $[identifier] to update only certain items inside an array in a document. It helps change specific parts without touching everything.

You want to change the price of only some products in a shopping cart.
You need to mark only certain tasks as done in a list of tasks.
You want to update the status of specific orders in an order history.
You want to fix the score of only some players in a game leaderboard.
Syntax
MongoDB
db.collection.updateOne(
  { <filter> },
  { $set: { "arrayField.$[identifier].fieldToUpdate": newValue } },
  { arrayFilters: [ { "identifier.conditionField": conditionValue } ] }
)

The $[identifier] is a placeholder for array elements that match the filter in arrayFilters.

You must provide arrayFilters to tell MongoDB which array items to update.

Examples
Updates Alice's Math grade score to 95 only.
MongoDB
db.students.updateOne(
  { name: "Alice" },
  { $set: { "grades.$[elem].score": 95 } },
  { arrayFilters: [ { "elem.subject": "Math" } ] }
)
Marks only packed items as shipped in order 123.
MongoDB
db.orders.updateOne(
  { orderId: 123 },
  { $set: { "items.$[item].shipped": true } },
  { arrayFilters: [ { "item.status": "packed" } ] }
)
Sets all Horror genre books as unavailable in City Library.
MongoDB
db.library.updateOne(
  { name: "City Library" },
  { $set: { "books.$[book].available": false } },
  { arrayFilters: [ { "book.genre": "Horror" } ] }
)
Sample Program

This example creates a user John with hobbies. It updates only hobbies of type 'sports' to have level 'expert'.

MongoDB
db.users.insertOne({
  name: "John",
  hobbies: [
    { type: "sports", name: "soccer", level: "beginner" },
    { type: "music", name: "guitar", level: "intermediate" },
    { type: "sports", name: "tennis", level: "advanced" }
  ]
});

// Before update
printjson(db.users.findOne({ name: "John" }));

// Update only sports hobbies to level "expert"
db.users.updateOne(
  { name: "John" },
  { $set: { "hobbies.$[hobby].level": "expert" } },
  { arrayFilters: [ { "hobby.type": "sports" } ] }
);

// After update
printjson(db.users.findOne({ name: "John" }));
OutputSuccess
Important Notes

Time complexity depends on the number of array elements and the filter conditions.

Space complexity is minimal as only matching elements are updated.

Common mistake: forgetting to include arrayFilters causes no update or error.

Use $[identifier] when you want to update specific array elements. Use $ positional operator only if you update the first matching element.

Summary

$[identifier] lets you update specific items inside arrays.

You must use arrayFilters to tell MongoDB which items to update.

This helps avoid changing the whole array or wrong elements.