Syntax error Appending an entry in one to many embedded documents with MongoDB

Appending an entry in one to many embedded documents with MongoDB



To append an entry in MongoDB, use $push. Let us create a collection with documents −

> db.demo253.insertOne(
...   {
...      _id: "101",
...      isActive: false,
...      details: [
...         {
...            Name: "Chris",
...         },
...         {
...            CountryName:"US"
...         }
...      ]
...   }
...);
{ "acknowledged" : true, "insertedId" : "101" }

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

> db.demo253.find();

This will produce the following output −

{ "_id" : "101", "isActive" : false, "details" : [ { "Name" : "Chris" }, { "CountryName" : "US" } ] }

Following is the query to append an entry in one to many embedded documents −

> db.demo253.update({_id: '101'}, {$push: {details: {Age: 21}}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo253.find();

This will produce the following output −

{ "_id" : "101", "isActive" : false, "details" : [ { "Name" : "Chris" }, { "CountryName" : "US" }, { "Age" : 21 } ] }
Updated on: 2020-03-30T14:34:24+05:30

341 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements