MongoDB

mongodb $addToSet

The $addToSet operator is among those array update() operators that MongoDB offers to update the array field value in documents. The $addToSet operator required unique entries to be added or appended in the specified array field. If a value is already present in the given array, then the $addToSet retrieves the exact array without modification. The $addToSet operator needs to make sure that an array will not contain any duplicate elements when it is updated but it is possible for the order of an array’s items to alter after a value has been added.

How to Use the MongoDB $addToSet Operator?

The $addToSet operator is employed inside the update() method of MongoDB. The $addToSet operator inputs the parameter “field” and the “addition”. The “field” indicates the column of the document to be updated. The “addition” is the parameter that is assigned the value to be inserted into the array to the corresponding field. Before using the $addToSet operator in the MongoDB query, we need to establish the collection. Here, we have a MongoDB collection of “Courses” to which we have applied the insertMany() query to add the following documents.

db.Courses.insertMany([
      {
          "_id": 1,
          "Field": "IT",
          "Courses" : ["Web Development", "Database", "Python"],
          "CreditHours":[5, 2, 7]
      },
       {
          "_id": 2,
          "Field": "CS",
          "Courses" : ["Python", "Networking", "Computing"],
          "CreditHours":[8, 4, 2]
      },
       {
          "_id": 3,
          "Field": "SE",
          "Courses" : ["Data Science", "Python", "IBM"],
          "CreditHours":[2, 9, 5]
      }

  ])

The outcome of adding the documents to the “Courses” collection is presented below.

{ acknowledged: true, insertedIds: { '0': 1, '1': 2, '2': 3 } }

Example # 1: Query of the $addToSet Operator in MongoDB to Append the Value in an Array Field

Here, we are appending the new value in the field by using the $addToSet operator. In the MongoDB query, we have employed the update() method on the collection “Courses”. The update() method further inputs the condition {“Field”: “CS”} before the $addToSet operator. Firstly, the document will be searched which is set with the value “CS” against the column “Field” in the collection. When the document will be matched then the $addToSet operator will proceed with the operator of appending the value. We have provided the $addToSet operator with the array field “Courses” to append a new value array element “Accounts”.

db.Courses.update({"Field": "CS"}, {$addToSet: {"Courses": "Accounts"}})

The output shows that the new array element “Accounts” is appended in the field “Courses”.

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

We have examined our collection to confirm the modification. The array field “Courses” is successfully modified with the new value “Accounts”.

{
    _id: 2,
    Field: 'CS',
    Courses: [ 'Python', 'Networking', 'Computing', 'Accounts' ],
    CreditHours: [ 8, 4, 2 ]
  }

Example # 2: Query of the $addToSet Operator in MongoDB to Add a New Field

In the query above, the $addToSet operator is utilized to append the new value in the existing field. Moreover, we can insert the new field in the document by using the $addToSet operator in the update() method. Let us have the following MongoDB query. We have set the update() method where the expression “{ “_id”: 2 }” is provided to match that particular document. Then, we assigned the $addToSet operator to add the new field along with the new value. Here, we have added the array field “Teacher” which does not exist in the documents of the collection “Courses”. The “Teachers” field is assigned with an array of teachers’ names.

db.Courses.update(
   { "_id": 2  },
   { $addToSet: { "Teachers": ["Mr Sam", "Ms Alice"]  } }
)

The “modifiedCount:1” in the following output shows that the document is updated with the new field “Teachers” and the array values.

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Now, when the documents are checked, it showed up with the new update results as follows:

{
    _id: 2,
    Field: 'CS',
    Courses: [ 'Python', 'Networking', 'Computing', 'Accounts' ],
    CreditHours: [ 8, 4, 2, 7, 3 ],
    Teachers: [ [ 'Mr Sam', 'Ms Alice' ] ]
  }

Example # 3: Query of the $addToSet Operator in MongoDB to Add an Array in the Existing Array

Additionally, we can add an entire new array to the already present array using the $addToSet operator. The entire array gets appended as a separate array. Here, we have given a query to this statement. We have an update() method to which we have assigned a condition {“_id”: 3} as a first parameter. So, the document with the “_id” number “3” will be matched with the update condition and then the next parameter will proceed. The next parameter of the update() method is the “$addToSet” method for adding the array to the existing array. We have specified the array “[ 3, 1, 2]” to the field “CreditHours”. This array will be added as a separate array within the existing array of the field “CreditHours”.

db.Courses.update(
   { "_id": 3 },
   { $addToSet: { "CreditHours": [ 3, 1, 2] } }
)

The following information indicates that the array is added to the present array:

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

The document shown below is updated with the new modification we have made.

{
    _id: 3,
    Field: 'SE',
    Courses: [ 'Data Science', 'Python', 'IBM' ],
    CreditHours: [ 2, 9, 5, [ 3, 1, 2 ] ]
  }

Example # 4: Query of the $addToSet Operator in MongoDB to Add Multiple Values

The $addToSet enables us to add more than one value at the same time in an array by taking the $each operator as a parameter. The $each operator is employed to append multiple entries to a provided array. Here, we have given a query where we have to satisfy the condition “{ “_id”: 2}” of the update() method. Then, we have the $addToSet operator where we have employed the $each operator to add the two values “7” and “3” in the field “CreditHours”.

db.Courses.update( { "_id": 2}, { $addToSet: { "CreditHours":{$each:[7,3]}}});

The above query executed displayed the confirmation output which indicates the values are inserted in the matched document.

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

The two array elements “7” and “3” are appended in the array field “CreditHours”.

{
    _id: 2,
    Field: 'CS',
    Courses: [ 'Python', 'Networking', 'Computing', 'Accounts' ],
    CreditHours: [ 8, 4, 2, 7, 3 ]
  }

Example # 5: Query of the $addToSet Operator in MongoDB to Add the Existing Value

When the array value is already present, we attempt to insert that value again in the field then the $addSetTo operator does nothing. To put it another way, $addToSet only adds a value if one does not already exist. There, we have given a query in the shell of the MongoDB where we utilized the update() method. Inside the update() method, we have passed the condition that the document has the “_id” equal to “1”. After that, we called the $addToSet operator which takes the field “Courses” with the “addition” parameter value “Database”. The “Database” already exists in the specified document so the $addToSet operator will not update this value.

db.Courses.update(
   { _id: 1 },
   { $addToSet: { "Courses": "Database" } }
)

We can see that the “modifiedCount” option has a “0” value which shows that the document is not modified.

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 0,
  upsertedCount: 0
}

The matched document is also checked below to display that already existing values cannot be added again by the $addToSet operator.

{
    _id: 1,
    Field: 'IT',
    Courses: [ 'Web Development', 'Database', 'Python' ],
    CreditHours: [ 5, 2, 7, 3 ]
  }

Conclusion

The article is all about the discussion of the MongoDB $addToSet operator. We have seen the $addToSet operation within the MongoDB update query. The first example is to $addToSet operator append the unique value in the array of the document. We have then added the non-existence field with the $addToSet operator. The new array is also appended to the already specified array. After this, we appended the array with multiple entries, and then we attempted to insert the duplicate value in the array with the $addToSet operator.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.