How to push an element into array in MongoDB?


To push an element into array, use $push. Let us first create a collection with documents −

> db.demo6.insertOne({"ListOfNames":["Bob","David","Mike","Sam"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0b6b3f25ddae1f53b62228")
}

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

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

This will produce the following output −

{
"_id" : ObjectId("5e0b6b3f25ddae1f53b62228"),
   "ListOfNames" : [
      "Bob",
      "David",
      "Mike",
      "Sam"
   ]
}

Here is the query to push an element into array in MongoDB −

> db.demo6.update({ _id: ObjectId("5e0b6b3f25ddae1f53b62228") },{ $push: { ListOfNames: "Robert" } });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e0b6b3f25ddae1f53b62228"),
   "ListOfNames" : [
      "Bob",
      "David",
      "Mike",
      "Sam",
      "Robert"
   ]
}

Updated on: 01-Apr-2020

269 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements