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
MongoDB $addToSet to add a deep nested array of object?
The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array. When working with deep nested arrays, combine $addToSet with the positional operator $ to target specific array elements.
Syntax
db.collection.update(
{ "parentArray.field": "matchValue" },
{ $addToSet: { "parentArray.$.nestedArray": newObject } }
);
Sample Data
Let us first create a collection with documents ?
db.demo380.insertOne({
"details": [
{
"Name": "Chris",
"details1": []
},
{
"Name": "David",
"details1": []
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e5b56e32ae06a1609a00b11")
}
Display all documents from a collection with the help of find() method ?
db.demo380.find().pretty();
{
"_id": ObjectId("5e5b56e32ae06a1609a00b11"),
"details": [
{
"Name": "Chris",
"details1": []
},
{
"Name": "David",
"details1": []
}
]
}
Example: Add Object to Nested Array
Following is the query to add a deep nested array of object ?
db.demo380.update({
"details.Name": "David"
}, {
$addToSet: {
"details.$.details1": {
"SubjectName": "MongoDB",
"TeacherName": "Bob"
}
}
});
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Display all documents from a collection with the help of find() method ?
db.demo380.find().pretty();
{
"_id": ObjectId("5e5b56e32ae06a1609a00b11"),
"details": [
{
"Name": "Chris",
"details1": []
},
{
"Name": "David",
"details1": [
{
"SubjectName": "MongoDB",
"TeacherName": "Bob"
}
]
}
]
}
Key Points
- Use
$positional operator to identify the matched array element -
$addToSetprevents duplicate objects from being added to the nested array - The query matches the parent array element by a specific field value
Conclusion
The $addToSet operator combined with the positional operator $ effectively adds objects to deep nested arrays while preventing duplicates. This approach ensures data integrity in complex nested document structures.
