
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Update 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": "[email protected]" }} ... ... } ... ) { "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" : "[email protected]" } ] } ] }
Advertisements