Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
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();
This will produce the following output −
{
"_id" : ObjectId("5e5b56e32ae06a1609a00b11"),
"details" : [
{
"Name" : "Chris",
"details1" : [ ]
},
{
"Name" : "David",
"details1" : [ ]
}
]
}
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"
... }
... }
... }, false, true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo380.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e5b56e32ae06a1609a00b11"),
"details" : [
{
"Name" : "Chris",
"details1" : [ ]
},
{
"Name" : "David",
"details1" : [
{
"SubjectName" : "MongoDB",
"TeacherName" : "Bob"
}
]
}
]
}Advertisements