We use $[identifier] to update only certain items inside an array in a document. It helps change specific parts without touching everything.
Array update with $[identifier] filtered in 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.
db.students.updateOne(
{ name: "Alice" },
{ $set: { "grades.$[elem].score": 95 } },
{ arrayFilters: [ { "elem.subject": "Math" } ] }
)db.orders.updateOne(
{ orderId: 123 },
{ $set: { "items.$[item].shipped": true } },
{ arrayFilters: [ { "item.status": "packed" } ] }
)db.library.updateOne(
{ name: "City Library" },
{ $set: { "books.$[book].available": false } },
{ arrayFilters: [ { "book.genre": "Horror" } ] }
)This example creates a user John with hobbies. It updates only hobbies of type 'sports' to have level 'expert'.
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" }));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.
$[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.