How to update a MongoDB document for adding a new item to an array?


To add a new item to an array, you can use $push operator. Let us first implement the following query to create a collection with documents:

> db.updateDemo.insertOne({"StudentName":"Larry","StudentCoreSubject":["Java","C"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c98ba78330fd0aa0d2fe4c9")
}
>db.updateDemo.insertOne({"StudentName":"Robert","StudentCoreSubject":["C++","MongoDB"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c98ba8b330fd0aa0d2fe4ca")
}
> db.updateDemo.insertOne({"StudentName":"Chris","StudentCoreSubject":["Python"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c98ba9b330fd0aa0d2fe4cb")
}

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

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

This will produce the following output

{
   "_id" : ObjectId("5c98ba78330fd0aa0d2fe4c9"),
   "StudentName" : "Larry",
   "StudentCoreSubject" : [
      "Java",
      "C"
   ]
}
{
   "_id" : ObjectId("5c98ba8b330fd0aa0d2fe4ca"),
   "StudentName" : "Robert",
   "StudentCoreSubject" : [
      "C++",
      "MongoDB"
   ]
}
{
   "_id" : ObjectId("5c98ba9b330fd0aa0d2fe4cb"),
   "StudentName" : "Chris",
   "StudentCoreSubject" : [
      "Python"
   ]
}

Following is the query to add a new item to an array

> db.updateDemo.update( { _id:ObjectId("5c98ba78330fd0aa0d2fe4c9") }, { $push: { "StudentCoreSubject": "MySQL" } });
Updated 1 existing record(s) in 2ms
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Now check the item is inserted into the array or not

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

This will produce the following output. The string “MySQL” inserted successfully in the id 5c98ba78330fd0aa0d2fe4c9

{
   "_id" : ObjectId("5c98ba78330fd0aa0d2fe4c9"),
   "StudentName" : "Larry",
   "StudentCoreSubject" : [
      "Java",
      "C",
      "MySQL"
   ]
}
{
   "_id" : ObjectId("5c98ba8b330fd0aa0d2fe4ca"),
   "StudentName" : "Robert",
   "StudentCoreSubject" : [
      "C++",
      "MongoDB"
   ]
}
{
   "_id" : ObjectId("5c98ba9b330fd0aa0d2fe4cb"),
   "StudentName" : "Chris",
   "StudentCoreSubject" : [
      "Python"
   ]
}

Updated on: 30-Jul-2019

198 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements