MongoDB Array Update Operator - $addToSet
Description
The $addToSet operator adds or appends a value to an array, only if the value does not exist in the array. The $addToSet returns the same array without modifying when the value already is in the array.
The $addToSet operator ensures that there will be no duplicate items in an array at the time of updating, but one thing can be happen that, after adding a value, the order of the elements of an array can be changed.
Syntax:
db.collection.update( { <field>: <value> }, { $addToSet: { <field>: <addition> } } );
Parameters:
Name | Description |
---|---|
field | name of the column or field to the document.. |
value | The value, specified against a field for an expression, or condition, or matching criteria. |
addition | The value of to be added for a field or column into an array if this value not exists. |
Sample collection "student"
{ "_id" : 1, "sem" : 1, "achieve" : [ 70, 87, 90 ] }
Example of MongoDB $addToSet operator to append a value
If we want to append a value 92 to the array achieve the following mongodb command can be used -
db.student.update( { "sem": 1}, { $addToSet: { "achieve": 92 } } );
The above example will append a value 92 in the array field achieve.
To see the newly updated document -
> db.student.find().pretty();
Output of the command
{ "_id" : 1, "achieve" : [ 70, 87, 90, 92 ], "sem" : 1 }
Example of MongoDB $addToSet operator to add multiple value using $each modifier
If we want to append the values 10 and 11 to the array field achieve, the following mongodb command can be used.
> db.student.update( { "sem": 1}, { $addToSet: { "achieve":{$each:[10,11]}}});
In the above example, using of $each modifier the values 10 and 11 have been appended to the array field achieve.
To see the newly updated document -
> db.student.find().pretty();
Output of the command:
{ "_id" : 1, "achieve" : [ 70, 87, 90, 92, 10, 11 ], "sem" : 1 }
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/mongodb/mongodb-array-update-operator-$addtoset.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics