MongoDB query to push document into an array


To push document into an array, use $push along with update(). Let us create a collection with documents −

>db.demo310.insertOne({"Name":"Chris","details":[{"Id":101,"Subject":"MySQL"},{"Id":102,"Subject":"MongoDB"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e50cabdf8647eb59e562043")
}

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

> db.demo310.find();

This will produce the following output −

{
   "_id" : ObjectId("5e50cabdf8647eb59e562043"), "Name" : "Chris", "details" : [
      { "Id" : 101, "Subject" : "MySQL" }, { "Id" : 102, "Subject" : "MongoDB" }
   ]
}

Following is the query to push document −

> db.demo310.update({ _id:ObjectId("5e50cabdf8647eb59e562043")},
...{ $push: {"details": {
...   "Id" : 103,
...   "Subject": "Java"
...   }}
...}
...)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo310.find();

This will produce the following output −

{
   "_id" : ObjectId("5e50cabdf8647eb59e562043"), "Name" : "Chris", "details" : [
      { "Id" : 101, "Subject" : "MySQL" }, { "Id" : 102, "Subject" : "MongoDB" },
      { "Id" : 103, "Subject" : "Java" }
   ] 
}

Updated on: 01-Apr-2020

301 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements