- 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 keep appending subdocuments in MongoDB?
To append subdocuments, use $push in MongoDB. The update() is used to update. Let us create a collection with documents −
> db.demo587.insertOne({"id":101,"details":[{Name:"Chris",Age:21,Marks:57}]});{ "acknowledged" : true, "insertedId" : ObjectId("5e92ba01fd2d90c177b5bcc9") } > db.demo587.insertOne({"id":102,"details":[{Name:"Bob",Age:22,Marks:78}]});{ "acknowledged" : true, "insertedId" : ObjectId("5e92ba0efd2d90c177b5bcca") }
Display all documents from a collection with the help of find() method −
> db.demo587.find();
This will produce the following output −
{ "_id" : ObjectId("5e92ba01fd2d90c177b5bcc9"), "id" : 101, "details" : [ { "Name" : "Chris", "Age" : 21, "Marks" : 57 } ] } { "_id" : ObjectId("5e92ba0efd2d90c177b5bcca"), "id" : 102, "details" : [ { "Name" : "Bob", "Age" : 22, "Marks" : 78 } ] }
Following is the query to keep appending subdocuments in MongoDB −
> db.demo587.update({"id":101}, {"$push": {"details":{Subject:"MongoDB"}}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo587.find();
This will produce the following output −
{ "_id" : ObjectId("5e92ba01fd2d90c177b5bcc9"), "id" : 101, "details" : [ { "Name" : "Chris", "Age" : 21, "Marks" : 57 }, { "Subject" : "MongoDB" } ] } { "_id" : ObjectId("5e92ba0efd2d90c177b5bcca"), "id" : 102, "details" : [ { "Name" : "Bob", "Age" : 22, "Marks" : 78 } ] }
Advertisements