How to Use $[] All Positional Operator in MongoDB
In MongoDB, the
$[] all positional operator lets you update all elements of an array in a document at once. Use it inside an update command with $set or other update operators to apply changes to every array element without specifying each index.Syntax
The $[] operator is used inside update statements to target all elements of an array field. It is placed inside the array field name in the update document.
{ $set: { 'arrayField.$[]': value } }updates all elements inarrayFieldtovalue.$[]works only with update operators like$set,$inc, etc.
json
{
"$set": {
"arrayField.$[]": <newValue>
}
}Example
This example updates all elements in the scores array by adding 5 to each score.
mongodb
db.students.updateMany(
{},
{ $inc: { "scores.$[]": 5 } }
);Output
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
Common Pitfalls
Common mistakes when using $[] include:
- Trying to use
$[]outside of update operators like$setor$inc. - Using
$[]on fields that are not arrays, which causes errors. - Confusing
$[]with the single positional operator$, which updates only the first matching element.
mongodb
/* Wrong: $[] used without update operator */ db.collection.updateMany({}, { "arrayField.$[]": 10 }); /* Right: $[] used with $set */ db.collection.updateMany({}, { $set: { "arrayField.$[]": 10 } });
Quick Reference
- $[]: Targets all elements in an array.
- Use only inside update operators like
$set,$inc,$mul, etc. - Works only on array fields.
- Different from
$which targets the first matching element.
Key Takeaways
Use
$[] to update all elements in an array field in MongoDB documents.$[] must be used inside update operators like $set or $inc.Do not use
$[] on non-array fields or outside update operators.$[] updates every element, unlike $ which updates only the first matched element.