

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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" } ] } ] }
- Related Questions & Answers
- How to add new item in nested array with MongoDB?
- How to retrieve a nested object in MongoDB?
- Increment a value in a MongoDB nested object?
- Implement MongoDB $addToSet for an array in an array and append a value
- MongoDB query to get array of nested string?
- Opposite of $addToSet to '$removeFromSet' in MongoDB?
- MongoDB query to sort nested array?
- MongoDB query to aggregate nested array
- Query array of nested string with MongoDB?
- Clearing items in a nested MongoDB array?
- Increment MongoDB value inside a nested array
- MongoDB $push in nested array?
- Group query upon nested object in MongoDB?
- Unable to implement $addToSet in MongoDB to fetch values of a single field?
- MongoDB Increment value inside nested array?
Advertisements