MongoDB $addToSet Operator
MongoDB $addToSet Operator adds a value to an array field in the document.
$addToSet Operator in MongoDB
The $addToSet operator in MongoDB is used to add a value to an array and if the value already exists in the array, then this operator will do nothing.
The $addToSet operator appends the whole array as a single element if the value is an array. To add each element of the value separately, the $each modifier can be used with the $addToSet operator.
It is compatible with various MongoDB environments like MongoDB Atlas, MongoDB Enterprise, and MongoDB Community.
Syntax
The syntax to use the $addToSet Operator in MongoDB is:
{ $addToSet: { <field1>: <value1>, ... } }
Here, <field> can specify with dot notation in embedded/nested documents.
MongoDB $addToSet Operator Examples
In the following examples, we are working with:
Database: w3wiki
Collection: contributor
Document: two documents that contain the details of the contributor in the form of field-value pairs.
Adding value in an array using $addToSet operator example
In this example, we are adding “JS++” value in the language array of document which satisfy the specified condition, i.e., name: “Rohit”.
Query:
db.contributor.update({name: "Rohit"}, {$addToSet: {language: "JS++"}})
Output:
Adding duplicate values in the array using $addToSet operator example:
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.
Query:
db.contributor.update({name: "Sumit"}, {$addToSet: {language: "Perl"}})
Output:
Using $each modifier with $addToSet operator example
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.
Query:
contributor.update({name: "Sumit"}, {$addToSet:
{language:{$each: ["Perl", "Go", "Ruby"]}}})
Output:
KeyTakeAways About $addToSet Operator
- $addToSet Operator inserts a new value to an array field in the document.
- 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
the 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.
Contact Us