MongoDB query to add new array element in document


To add new array element in a MongoDB document, use $(projection) along with update(). Let us create a collection with documents −

>db.demo222.insertOne({"details":[{"StudentName":"Chris","StudentMarks":78},{"StudentName":"David","StudentMarks":89}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3ee31703d395bdc213472f")
}

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

> db.demo222.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e3ee31703d395bdc213472f"),
   "details" : [
      {
         "StudentName" : "Chris",
         "StudentMarks" : 78
      },
      {
         "StudentName" : "David",
         "StudentMarks" : 89
      }
   ]
}

Following is the query to add new array element in document −

> db.demo222.update({"details.StudentName" : "Chris"},{"$set" : {"details.$.SubjectName":"MongoDB"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo222.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e3ee31703d395bdc213472f"),
   "details" : [
      {
         "StudentName" : "Chris",
         "StudentMarks" : 78,
         "SubjectName" : "MongoDB"
      },
      {
         "StudentName" : "David",
         "StudentMarks" : 89
      }
   ]
}

Updated on: 30-Mar-2020

384 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements