Open In App

MongoDB – All Positional Operator ($[])

Improve
Improve
Like Article
Like
Save
Share
Report

MongoDB provides different types of array update operators to update the values of the array fields in the documents and all positional operator($[]) is one of them. This operator indicates that the update operation should modify all the items present in the specified array field. Syntax: 

{ <update operator>: { "<array>.$[]" : <value> } }
  • You can also use this operator for those queries which traverse more than one array and nested arrays.
  • If upsert is set to true, then the query must contain an exact equality match on the array field in order to use $[] operator in the update statement. If upsert operation doesnot include the exact equality match on the array field, then upsert will give an error.
  • You can use $[] operator with update(), findAndModify(), etc., methods to modify all the array items for the document or documents that match the specified query condition.

In the following examples, we are working with: 

Database: GeeksforGeeks 

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:

In this example, we are updating by incrementing all the items by 10 of points field. 

Python3




db.contributor.update({}, {$inc: {"points.$[]": 5}}, {multi: true})


Updating all the documents in the array:

In this example, we are updating by decrementing the value of the tArticles field by -10 for all the items in the articles array. 

Python3




db.contributor.update({}, {$inc: {"articles.$[].tArticles": -10}},
                           {multi: true})


Updating an array using a negation query operator:

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. 

Python3




db.contributor.update({points: {$ne: 25}},
                      {$inc: {"points.$[]": 20}},
                        {multi: true})


Updating the nested array in conjunction with $[< identifier>]:

In this example, we are updating all the values that are less than or equal to 80 in the nested marks.firstsemester array. 

Python3




db.contributor.update({}, {$inc: {"marks.$[].firstsemester.$[newmarks]": 3}},
                            {arrayFilters: [{newmarks: {$lte: 80}}], multi: true})




Last Updated : 13 May, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads