Open In App

MongoDB – All Positional Operator ($[])

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> } }

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. 




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. 




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. 




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. 




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


Article Tags :