Script to add a single value to array in MongoDB collection?


To add only a single value to array, use $push. Let us first create a collection with documents −

> db.demo3.insertOne(
...    {
...       "Information" : {
...          "Of" : {
...             "StudentCode" : "STUDENT101",
...             "StudentFavouriteSubject" : [
...                "MySQL",
...                "Java"
...             ]
...          }
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e08b7ef25ddae1f53b6221b")
}

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

> db.demo3.find();

This will produce the following output −

{ "_id" : ObjectId("5e08b7ef25ddae1f53b6221b"), "Information" : { "Of" : { "StudentCode" : "STUDENT101", "StudentFavouriteSubject" : [ "MySQL", "Java" ] } } }

Here is the query to add only a single value to array in MongoDB −

> db.demo3.update({},{$push:{"Information.Of.StudentFavouriteSubject":"Spring and Hibernate"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check all the documents once again −

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

This will produce the following output −

{
   "_id" : ObjectId("5e08b7ef25ddae1f53b6221b"),
   "Information" : {
      "Of" : {
         "StudentCode" : "STUDENT101",
         "StudentFavouriteSubject" : [
            "MySQL",
            "Java",
            "Spring and Hibernate"
         ]
      }
   }
}

Updated on: 31-Mar-2020

166 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements