
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 Array Element Matching a Condition Using Push in MongoDB
For this, use update command and $push. Let us first create a collection with documents −
>db.demo9.insertOne({"StudentDetails":[{"StudentName":"Chris","ListOfSubject":["MySQL","Java"]}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e0f6438d7df943a7cec4f94") }
Following is the query to display all documents from a collection with the help of find() method −
> db.demo9.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e0f6438d7df943a7cec4f94"), "StudentDetails" : [ { "StudentName" : "Chris", "ListOfSubject" : [ "MySQL", "Java" ] } ] }
Following is the query to update an array element matching a condition using $push −
> db.demo9.update( { "StudentDetails.StudentName":"Chris"}, {$push:{"StudentDetails.$.ListOfSubject":"MongoDB"}}); 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.demo9.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e0f6438d7df943a7cec4f94"), "StudentDetails" : [ { "StudentName" : "Chris", "ListOfSubject" : [ "MySQL", "Java", "MongoDB" ] } ] }
Advertisements