MongoDB All Positional Operator Example
Let’s look at some examples of the All Positional Operator in MongoDB to understand it better.
In the following examples, we are working with:
Database: w3wiki
Collection: contributor
Document: two documents that contain the details of the contributor in the form of field-value pairs.
Updating all the items in an array using All Positional Operator example:
In this example, we are updating by incrementing all the items by 10 of points field.
Query:
db.contributor.update({}, {$inc: {"points.$[]": 5}}, {multi: true})
Output:
Updating all the documents in the array using All Positional Operator example
In this example, we are updating by decrementing the value of the tArticles field by -10 for all the items in the articles array.
Query:
db.contributor.update({}, {$inc: {"articles.$[].tArticles": -10}}, {multi: true})
Output:
Updating an array using a negation query operator example:
In this example, we are incrementing all the items in the points array by 20 for all documents except those with the value 100 in the points array.
Query:
db.contributor.update({points: {$ne: 25}}, {$inc: {"points.$[]": 20}}, {multi: true})
Output:
Updating the nested array in conjunction with $[< identifier>] example:
In this example, we are updating all the values that are less than or equal to 80 in the nested marks.firstsemester array.
Query:
db.contributor.update({}, {$inc: {"marks.$[].firstsemester.$[newmarks]": 3}},
{arrayFilters: [{newmarks: {$lte: 80}}], multi: true})
Output:
] example output" height="inherit" loading="lazy" src="/public/files/example-42.jpg" width="inherit">
MongoDB All Positional Operator ($[])
MongoDB All Positional Operator allows bulk updates to all elements in an array field that matches the given query condition.