Positional and Filtered Positional Updates
Learners will update matched array elements in place using the $ positional operator and the $[identifier] filtered positional operator.
Updating Elements Inside Arrays
While $push and $pull add and remove array elements, sometimes you need to modify an existing element in place—change a field inside a sub-document that is already in the array. MongoDB provides two positional operators for this: the $ positional operator for updating the first matching element, and the $[identifier] filtered positional operator for updating all matching elements.
The $ Positional Operator
The $ positional operator acts as a placeholder for the index of the first array element that matched the query filter. You use it in the update's field path like 'arrayField.$.subField', and MongoDB replaces $ with the index of the matched element. The query filter must include a condition on the array field so MongoDB knows which element to target.
// Update the grade of the first matching scores element
db.students.updateOne(
{
_id: studentId,
'scores.subject': 'math' // match condition identifies which element
},
{
$set: { 'scores.$.grade': 'A+' } // $ = index of matched element
}
);
// Only the FIRST element where subject='math' is updatedAll lessons in this course
- Querying Arrays: $all, $size, and Element Match
- $elemMatch: Matching Array Sub-Documents
- Updating Arrays: $push, $pull, $pop, $addToSet
- Positional and Filtered Positional Updates