MongoDB $addToSet Operator Tutorial for Beginners

Опубликовано: 30 Июнь 2026
на канале: Fratello Innotech
7
0

MongoDB - $addToSet Array Operator

Definition

The $addToSet array update operator in MongoDB is used to add a value to an array only if the value does not already exist in the array. It prevents duplicate entries and ensures that each value in the array remains unique.

Steps to Use $addToSet Array Operator in MongoDB

1). Open the MongoDB Shell using mongosh.

2). Select the database using use database_name.

3). Check the existing documents using find().

4). Use the $addToSet operator with the updateOne() or updateMany() method.

5). Specify the document to update using a filter condition.

6). Specify the array field and the value to be added.

7). Execute the update query.

8). Verify the updated document using find().

Example
use studentdb

db.students.updateOne(
{
roll_no: 101
},
{
$addToSet: {
subjects: "Java"
}
}
)

Explanation:
This query adds Java to the subjects array only if it is not already present. If Java already exists in the array, no duplicate value is added.