- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to add a sub-document to sub-document array in MongoDB?
Use the $push operator to add a sub-document. Let us first create a collection with documents −
> db.subDocumentToSubDocumentDemo.insertOne( { "_id" :101, "StudentName" : "Larry", "StudentAge" : 21, "StudentDetails" : [ { "StudentCountryName" : "US", "StudentFavouriteSubjectList" : [ ] } ] } ); { "acknowledged" : true, "insertedId" : 101 }
Following is the query to display all documents from a collection with the help of find() method −
> db.subDocumentToSubDocumentDemo.find().pretty();
This will produce the following output −
{ "_id" : 101, "StudentName" : "Larry", "StudentAge" : 21, "StudentDetails" : [ { "StudentCountryName" : "US", "StudentFavouriteSubjectList" : [ ] } ] }
Following is the query to add a sub-document to sub-document array in MongoDB −
> db.subDocumentToSubDocumentDemo.update( { "_id": 101 }, { "$push": { "StudentDetails": { "StudentCountryName" : "UK", "StudentFavouriteSubjectList" : ["MongoDB","Java" ] } } } ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check all the documents once again −
> db.subDocumentToSubDocumentDemo.find().pretty();
This will produce the following output −
{ "_id" : 101, "StudentName" : "Larry", "StudentAge" : 21, "StudentDetails" : [ { "StudentCountryName" : "US", "StudentFavouriteSubjectList" : [ ] }, { "StudentCountryName" : "UK", "StudentFavouriteSubjectList" : [ "MongoDB", "Java" ] } ] }
Advertisements