Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Is it possible to utilize $addToSet multiple times in the same update?
Yes, it is possible to use $addToSet multiple times in the same update operation. You can specify multiple fields or use the $each modifier to add multiple values to the same array in a single operation.
Syntax
// Multiple $addToSet operations
db.collection.update(
{ query },
{
$addToSet: {
"field1": "value1",
"field2": "value2"
}
}
);
// Adding multiple values to same array
db.collection.update(
{ query },
{
$addToSet: {
"arrayField": { $each: ["value1", "value2", "value3"] }
}
}
);
Sample Data
db.demo27.insertMany([
{"StudentDetails": {"101": {"Subject": ["Java"]}}},
{"StudentDetails": {"101": {"Subject": ["MySQL"]}}}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e15f9e822d07d3b95082e7f"),
ObjectId("5e15f9eb22d07d3b95082e80")
]
}
Initial Data
db.demo27.find().pretty();
{
"_id": ObjectId("5e15f9e822d07d3b95082e7f"),
"StudentDetails": {
"101": {
"Subject": ["Java"]
}
}
}
{
"_id": ObjectId("5e15f9eb22d07d3b95082e80"),
"StudentDetails": {
"101": {
"Subject": ["MySQL"]
}
}
}
Method 1: Multiple Values with $each
Add multiple subjects to the first document using $addToSet with $each ?
db.demo27.update(
{"StudentDetails.101.Subject": "Java"},
{
$addToSet: {
"StudentDetails.101.Subject": {
$each: ["MongoDB", "Python", "JavaScript"]
}
}
}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Method 2: Single Value Addition
Add a single subject to the second document ?
db.demo27.update(
{"StudentDetails.101.Subject": "MySQL"},
{
$addToSet: {
"StudentDetails.101.Subject": "MongoDB"
}
}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Results
db.demo27.find().pretty();
{
"_id": ObjectId("5e15f9e822d07d3b95082e7f"),
"StudentDetails": {
"101": {
"Subject": ["Java", "MongoDB", "Python", "JavaScript"]
}
}
}
{
"_id": ObjectId("5e15f9eb22d07d3b95082e80"),
"StudentDetails": {
"101": {
"Subject": ["MySQL", "MongoDB"]
}
}
}
Key Points
-
$addToSetprevents duplicate values in arrays - Use
$eachmodifier to add multiple values in one operation - Multiple
$addToSetoperations can target different fields simultaneously
Conclusion
MongoDB supports multiple $addToSet operations in a single update. Use the $each modifier to add multiple values efficiently while maintaining array uniqueness.
Advertisements
