MongoDB addToSet: Simplifying Array Operations
Adam C. |

MongoDB is a popular NoSQL database that offers a variety of features to make working with data easier and more efficient. One of these features is the $addToSet operation, which allows you to add a new element to an array field only if it does not already exist in the array.

Photo by Jessica Ruscello on Unsplash

The $addToSet operation is available in both the MongoDB shell and in most programming languages that have a MongoDB driver. It is especially useful when working with arrays that contain unique values, such as a list of tags or categories.

Consider the following example, where we have a collection of products, each with an array field called tags, which contains a list of tags associated with the product:

{
  _id: 1,
  name: "Product 1",
  tags: ["tag1", "tag2"]
},
{
  _id: 2,
  name: "Product 2",
  tags: ["tag2", "tag3"]
}

To add a new tag to the tags array of a product with a given _id, we can use the $addToSet operator as follows:

db.products.update({_id: 1}, {$addToSet: {tags: "newTag"}})

This will add the value "newTag" to the tags array of the product with _id equal to 1, only if it does not already exist in the array.

Before I knew about the addToSet operation in MongoDB, I used to perform the tag updating in two steps. First, I would find the product using findOne() and then check if the new tag already exists in the tags array using in_array($newTag, $product['tags']). If it's found, I would skip the update; otherwise, I would add the new tag to the tags array and update the record. Here's an example of what the code might look like in PHP:

// Find the product with _id = 1
$product = $collection->findOne(['_id' => 1]);

// Check if the new tag already exists in the tags array
if (!in_array($newTag, $product['tags'])) {
    // Add the new tag to the tags array
    $product['tags'][] = $newTag;
    
    // Update the record
    $collection->updateOne(['_id' => 1], ['$set' => ['tags' => $product['tags']]]);
}

This can be done by using the addToSet operation like below:

$result = $collection->updateOne(
    ['_id' => 1],
    ['$addToSet' => ['tags' => $newTag ]]
);

It's important to note that the addToSet operation only works with arrays including associative arrays, and it does not work with subdocuments or other complex data types. Additionally, the addToSet operation can be slower than other operations, especially when working with large arrays, so it's important to use it wisely and only when necessary.

In conclusion, the addToSet operation in MongoDB is a powerful tool that allows you to add unique values to an array field with ease. Whether you're working in the MongoDB shell or in a programming language like PHP, the addToSet operation is a great way to manage arrays and ensure that they contain only unique values.