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:
MongoDB $addToSet Operator
MongoDB $addToSet Operator adds a value to an array field in the document.