Open In App

MongoDB – Positional Operator ($)

MongoDB provides different types of array update operators to update the values of the array fields in the documents and positional operator( $ ) is one of them. This operator recognizes an element in an array to update without explicitly specifying the position of that item in the array.

Syntax:



{ "<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 values in the array using $ operator:

In this example, we are updating the first item whose value is “Python” to “Ruby” in the language field with the help of $ operator, because we don’t know the position of the item in the array.




db.contributor.updateOne({name: "Rohit", language: "Python"}, 
                         {$set: {"language.$": "Ruby"}})

Here, the $ operator is working as a placeholder for the first match of the update query document.

Note: The array field must be the part of the query.

Updating documents in the array using $ operator:

In this example, we are updating an array that contains embedded documents with the help of $ operator and to access embedded document fields we use dot notation. Or in other words, we are updating the value of tArticle field from 60 to 100.




db.contributor.updateOne({name: "Rohit", "articles.language": "C#"}, 
                         {$set: {"articles.$.tArticles": 100}})

Updating embedded documents using multiple field matches:

In this example, we are updating the value of the tArticles field in the first embedded document that has a pArticles field with a value greater than 90.




db.contributor.updateOne({name: "Sumit", articles: {$elemMatch:
                                          {pArticles: {$gt: 30}}}},
                             {$set: {"articles.$.tArticles": 200}})


Article Tags :