Updating an array with $push in MongoDB



To update an array with $push, use updateOne() in MongoDB. Let us create a collection with documents −

> db.demo526.insertOne( ... { ... ...    "CountryName": "US", ...    "TeacherName": "Bob", ...    "StudentInformation": [ ...       { ...          "Name": "Chris", ...          "Subject": "MySQL", ...          "ListOfMailId":[] ...       }, ...       { ...          "Name": "David", ...          "Subject": "MongoDB", ...          "ListOfMailId":[] ... ...       } ...    ] ... } ... ); {    "acknowledged" : true,    "insertedId" : ObjectId("5e8af031437efc8605595b6b") }

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

> db.demo526.find();

This will produce the following output −

{ "_id" : ObjectId("5e8af031437efc8605595b6b"), "CountryName" : "US", "TeacherName" : "Bob", "StudentInformation" : [ { "Name" : "Chris", "Subject" : "MySQL", "ListOfMailId" : [ ] }, { "Name" : "David", "Subject" : "MongoDB", "ListOfMailId" : [ ] } ] }

Following is the query to update an array with $push −

> db.demo526.updateOne( ... { ...    _id:ObjectId("5e8af031437efc8605595b6b"), ...    "StudentInformation": { "$elemMatch": { "Name": "David", "Subject": "MongoDB" }} ... }, ... { ...    "$push": { "StudentInformation.$.ListOfMailId": { "MailId": "David@gmail.com" }} ... ... } ... ) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

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

> db.demo526.find();

This will produce the following output −

{ "_id" : ObjectId("5e8af031437efc8605595b6b"), "CountryName" : "US", "TeacherName" : "Bob", "StudentInformation" : [    { "Name" : "Chris", "Subject" : "MySQL", "ListOfMailId" : [ ] },    { "Name" : "David", "Subject" : "MongoDB", "ListOfMailId" : [ { "MailId" : "David@gmail.com" } ] } ] }
Updated on: 2020-05-13T07:35:21+05:30

458 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements