Updating an array with $push in MongoDB

MongoDBDatabaseBig Data Analytics

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" } ] }
] }
raja
Published on 13-May-2020 11:04:21
Advertisements