Open In App

MongoDB – $addToSet Operator

MongoDB provides different types of array update operators to update the values of the array fields in the documents and $addToSet operator is one of them. This operator is used to add a value to an array and if the value already exists in the array, then this operator will do nothing.

Syntax:



{ $addToSet: { <field1>: <value1>, ... } }

Here, <field> can specify with dot notation in embedded/nested documents.

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.

Adding value in an array:

In this example, we are adding “JS++” value in the language array of document which satisfy the specified condition, i.e., name: “Rohit”.




db.contributor.update({name: "Rohit"}, {$addToSet: {language: "JS++"}})

Adding duplicate values in the array:

In this example, we are adding “Perl” value in the language array of document which satisfy the specified condition, i.e., name: “Sumit”. But $addToSet operator does not add this value in the language array because it already exists in the language array.




db.contributor.update({name: "Sumit"}, {$addToSet: {language: "Perl"}})

Using $each modifier with $addToSet operator:

In this example, we are adding multiple values, i.e., [“Perl”, “Go”, “Ruby”] in the language array with the help of $each modifier. Here, “Perl” doesnot add in the array because it already exists.




db.contributor.update({name: "Sumit"}, {$addToSet: 
                      {language:{$each: ["Perl", "Go", "Ruby"]}}})


Article Tags :