Open In App

MongoDB – $addToSet 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 $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.

  • This operator does not insert duplicate items in the array and does not affect already present duplicate items. Here, the order of the values does not matter.
  • If the specified field in the $addToSet operator is not present in the document, then this operator creates an array field in the document with values or items.
  • Is the specified value is an array in the $addToSet operator, then this operator will append the whole array as a single item. Or if you want to add items separately in the array, then use $each modifier.
  • This operator does not work with non-array fields.
  • If the value is a document, then MongoDB checks if the document exists or not in the array. If the specified document contains same field and value and the order of the field is also same as the existing document, then the specified document is a duplicate document as a result $addToSet operator does not add such documents in the array.
  • You can use this operator with methods like update(), findAndModify(), etc., according to your requirement.

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"]}}})




Last Updated : 01 Jun, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads