MongoDB query to insert an array element with a condition?


Let us first create a collection with documents −

>db.demo11.insertOne({"ListOfStudent":[{"StudentName":"Chris","ListOfScore":[76,67,54,89]}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0f6e34d7df943a7cec4fa1")
}

Following is the query to display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5e0f6e34d7df943a7cec4fa1"),
   "ListOfStudent" : [
      {
         "StudentName" : "Chris",
         "ListOfScore" : [
            76,
            67,
            54,
            89
         ]
      }
   ]
}

Here is the query to insert an array element with a condition −

> db.demo11.update( {"ListOfStudent.StudentName":"Chris"}, {$push:{"ListOfStudent.$.ListOfScore":98}} );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check the documents once again −

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

This will produce the following output −

{
   "_id" : ObjectId("5e0f6e34d7df943a7cec4fa1"),
   "ListOfStudent" : [
      {
         "StudentName" : "Chris",
         "ListOfScore" : [
            76,
            67,
            54,
            89,
            98
         ]
      }
   ]
}

Updated on: 01-Apr-2020

513 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements