Implement MongoDB $push in embedded document array?

MongoDBDatabaseBig Data Analytics

Let us create a collection with documents −

>db.demo288.insertOne({"Name":"Chris",details:[{"CountryName":"US",Marks:78},{"CountryName":"UK",Marks:68}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4c0393f49383b52759cbbe")
}

Display all documents from a collection with the help of find() method −

> db.demo288.find();

This will produce the following output −

{ "_id" : ObjectId("5e4c0393f49383b52759cbbe"), "Name" : "Chris", "details" : [ { "CountryName" : "US", "Marks" : 78 }, { "CountryName" : "UK", "Marks" : 68 } ] }

Following is the query to implement $push in embedded document array −

> db.demo288.update( {Name: "Chris"}, {$push:{ "details":{"CountryName" : "AUS", "Marks" : 98} }}, {upsert:true});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Display all documents from a collection with the help of find() method −

> db.demo288.find();

This will produce the following output −

{
   "_id" : ObjectId("5e4c0393f49383b52759cbbe"), "Name" : "Chris", "details" : [
      { "CountryName" : "US", "Marks" : 78 }, { "CountryName" : "UK", "Marks" : 68 },
      { "CountryName" : "AUS", "Marks" : 98 }
   ] 
}
raja
Published on 31-Mar-2020 17:15:57
Advertisements