How to keep appending subdocuments in MongoDB?

MongoDBDatabaseBig Data Analytics

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 } 
] }
raja
Published on 15-May-2020 06:44:06
Advertisements