$[<identifier>]
The $[<identifier>] filtered positional operator updates all array elements that match the specified filter conditions. It is used with the arrayFilters option to selectively update array elements.
Parameters
-
field.$[identifier]: The array field with the filtered positional operator. -
arrayFilters: An array of filter conditions that determine which elements to update.
Example (MongoDB Shell)
The following example demonstrates using the $[<identifier>] operator to update specific array elements based on a condition.
Create sample documents
db.students.insertOne({ _id: 1, name: "Alice", grades: [ { subject: "Math", score: 85 }, { subject: "Science", score: 92 }, { subject: "History", score: 78 } ] });
Query example
db.students.updateOne( { _id: 1 }, { $inc: { "grades.$[elem].score": 5 } }, { arrayFilters: [{ "elem.score": { $gte: 80 } }] } );
Output
{
"_id" : 1,
"name" : "Alice",
"grades" : [
{ "subject" : "Math", "score" : 90 },
{ "subject" : "Science", "score" : 97 },
{ "subject" : "History", "score" : 78 }
]
}
Code examples
To view a code example for using the $[<identifier>] operator, choose the tab for the language that you want to use: