What is the $addToSet operator in MongoDB?
MongoDB is a NoSQL database that stores data records in documents and not as rows and columns in tabular form. These documents are then grouped into collections.
Documents can be created, read, updated, and deleted, known as CRUD. To update existing document(s) within a collection, the following operations are available:
db.collection.updateOne()db.collection.updateMany()db.collection.replaceOne()
All of the operations above can manipulate fields using operators. In this Answer, we'll discuss one such $addToSet operator. Other Array Update Operators are:
$$[]$[<identifier>]$pop$pull$push$pullAll
Note: For this Answer, we'll use the
typescollection in thenumbersdatabase with four documents, as shown below:
Description
The $addToSet operator is used to add an element in an array if it isn't already present. If the element already exists in the array, nothing happens.
While this operator prevents the insertion of duplicate elements, it can do nothing about the duplicate elements that may already exist in the array. Additionally, the ordering of the inserted elements can't be guaranteed.
Note: As this operator is an Array Update Operator, using it on a field that is not an array will result in an error!
Syntax
The following code snippet shows the syntax for the $addToSet operator.
{$addToSet: {<field1>: <value1>,...}}
How to use $addToSeton an array
The code below is used to an insert an element (vals array of the document with _id
// Syntaxdb.types.updateOne({_id: 0},{$addToSet: {vals: 10}});// Printingdb.types.find({"_id":0})
How to use $addToSetto insert a duplicate value
If we try to add the element with value
// Syntaxdb.types.updateOne({_id: 0},{$addToSet: {vals: 2}});// Printingdb.types.find({"_id":0})
How to use $addToSeton a non-existent field
If this operator is used on a field that doesn't exist in the specified document, then that field is inserted into the document with the provided value as an array. This can be seen from the code snippet below which results in the addition of the words field into the document with _id
// Syntaxdb.types.updateOne({_id: 0},{$addToSet: {words: "one"}});// Printingdb.types.find({"_id":0})
How to use $addToSetto insert a value that's an array
Finally, if the value to add to the specified field is an array itself, then it's appended as a single element. For example, if we try to insert vals field of the document with _idvals field is updated to
// Syntaxdb.types.updateOne({_id: 1},{$addToSet: {vals: [11,13]}});// Printingdb.types.find({"_id":1})
Demo
The previously mentioned code snippets can be executed in the terminal below.
Free Resources