Ultimate Guide to Using $addToSet Operator in MongoDB

The $addToSet operator adds values ​​to the array if they are not present. If a duplicate value exists when adding a new value to the array, the new value will not be added.

Arrays are very important in JavaScript, especially when creating lists. Technically, an array is referred to as a special variable that can store different types of values in it. It can store strings, numbers, objects, and even arrays. An array can also be used in MongoDB documents to store values ​​of different types.

The $addToSet operator in MongoDB works more like the push function in JavaScript. However, the push function doesn’t check for duplicate items. It will simply add values to the specified array.

This article will teach you how to use the $addToSet operator in MongoDB with the help of Mongoose. We will also create a small Nodejs application to demonstrate with an example. So let’s get started.

Also Read: Difference Between MongoDB vs Mongoose

$addToSet

$addToSet adds a value to the array if the value does not exist if it already exists $addToSet does nothing for that array.

Syntax:

{ $addToSet: { <field>: <value> } }

If the specified <field> does not exist in the array, this operator will create it with the <value> passed.

Note:

$addToSet operator cannot be used for non-array fields.

Using $addToSet Operator in MongoDB

Let’s create a Nodejs application to be able to demonstrate the usage of the $addToSet operator with a clear example. Here are the steps below to get you started.

  • Create a Nodejs project directory and get into it:
mkdir nodeaddToSet
cd nodeaddToSet
  • Initialise a Nodejs project inside the project directory using the below command:
npm init -y

Once you pass this command, you should see a package.json file created in your project directory.

  • Next, create the entry point JavaScript file:
touch app.js
  • Install the required NPM packages for our project:
npm i express mongoose
  • Next, let us import all of the packages we installed. As a default behaviour, all third-party NPM packages that we install, get stored inside the node_modules directory. Paste this code into the app.js file.
const express = require('express');
const app = express();
const mongoose = require('mongoose');
  • Next, we shall set up a connection with a local MongoDB database. We will use Mongoose for this:
mongoose.connect('mongodb://localhost:27017/farmAndDairyDB', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
        console.log(`YAY! CONNECTED TO MONGO!`);
    })
    .catch((err) => {
        console.log(`UH OH! MONGO CONNECTION ERROR!`);
        console.log(err);
    })
  • Next, at the end of the app.js file, it is required to set up a localhost port for the app server to listen:
app.listen(8000, () => {
    console.log('Connected to PORT 8000...');
})
  • Next, we will create a new directory named models in our project directory.
mkdir models
  • Create a new file inside the directory named harvests.js, or anything you’d like.
touch models/harvests.js
  • We can now import Mongoose here as well so that we are able to create a schema for our farm and dairy products and the associated model.
const mongoose = require('mongoose');

const productsSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    price: {
        type: Number,
        required: true,
        min: 0
    },
    category: {
        type: String,
        lowercase: true,
        enum: ['fruit', 'vegetable', 'dairy']
    },
});

const Product = mongoose.model('Product', productsSchema);
  • To use the $addToSet operator on our documents, we have already added a few documents:
{ "_id" : ObjectId("6054f4ba0e761c066439114b"), "name" : "Fairy Eggplant", "price" : 1, "category" : "vegetable", "__v" : 0 }
{ "_id" : ObjectId("6054f4ba0e761c066439114c"), "name" : "Organic Goddess Melon", "price" : 4.99, "category" : "fruit", "__v" : 0 }
{ "_id" : ObjectId("6054f4ba0e761c066439114d"), "name" : "Organic Mini Seedless Watermelon", "price" : 3.99, "category" : "fruit", "__v" : 0 }
{ "_id" : ObjectId("6054f4ba0e761c066439114e"), "name" : "Organic Celery", "price" : 1.5, "category" : "vegetable", "__v" : 0 }
{ "_id" : ObjectId("6054f4ba0e761c066439114f"), "name" : "Chocolate Whole Milk", "price" : 2.69, "category" : "dairy", "__v" : 0 }
{ "_id" : ObjectId("6054f4ba0e761c066432875g"), "name" : "Fresh Orange Juice", "price" : 1.52, "category" : "fruit", "__v" : 0 }
  • Let’s say we updated our Mongoose schema after we created and saved these documents. Now, we also want to add “juice” to our category key. So, for the last document, which is “Fresh Orange Juice”, we want to keep the “fruit” value but also add the “juice” value to that array. To do so, we will simply use the $addToSet operator with update():
Product.update({
    "$addToSet": { "category": "juice" }
}, function (err, doc) {
    if (err) throw error;
    console.log(`Category updated for: ${doc.name}`);
    console.log(doc);
});

Now, this is what our console prints.

Output:

Category updated for Fresh Orange Juice

{
    "_id" : ObjectId("6054f4ba0e761c066432875g"), 
    "name" : "Fresh Orange Juice", 
    "price" : 1.52, 
    "category" : [
        "fruit", 
        "juice"
    ], 

This way we have successfully used the $addToSet operator in MongoDB with the help of Mongoose in a Nodejs application.

Read More: Building “Related Post” Engine Using MongoDB Aggregation

Conclusion

In this tutorial, we have learned to use $addToSet operators in MongoDB. The $addToSet operator is used in the MongoDB documentation to add a value to a field in an array or in an array of objects, and if the value already exists it does nothing, if the field doesn’t exist it creates it with the given value. We have also seen the demonstration of the $addToSet operation in MongoDB using Mongoose and Node.js, which helps you understand it better.

Reference

https://www.mongodb.com/docs/manual/reference/operator/update/addToSet/

Aneesha S
Aneesha S
Articles: 173