
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
Push New Items to an Array Inside an Object in MongoDB
You can use $elemMatch operator for this. Let us first create a collection with documents −
> db.pushNewItemsDemo.insertOne( { "_id" :1, "StudentScore" : 56, "StudentOtherDetails" : [ { "StudentName" : "John", "StudentFriendName" : [ "Bob", "Carol" ] }, { "StudentName" : "David", "StudentFriendName" : [ "Mike", "Sam" ] } ] } ); { "acknowledged" : true, "insertedId" : 1 }
Following is the query to display all documents from a collection with the help of find() method −
> db.pushNewItemsDemo.find();
This will produce the following output −
{ "_id" : 1, "StudentScore" : 56, "StudentOtherDetails" : [ { "StudentName" : "John", "StudentFriendName" : [ "Bob", "Carol" ] }, { "StudentName" : "David", "StudentFriendName" : [ "Mike", "Sam" ] } ] }
Following is the query to push new items to an array inside of an object −
>db.pushNewItemsDemo.update({"_id":1,"StudentOtherDetails":{"$elemMatch":{"StudentName":"David"}}}, {"$push":{"StudentOtherDetails.$.StudentFriendName":"James"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the documents once again −
> db.pushNewItemsDemo.find();
This will produce the following output −
{ "_id" : 1, "StudentScore" : 56, "StudentOtherDetails" : [ { "StudentName" : "John", "StudentFriendName" : [ "Bob", "Carol" ] }, { "StudentName" : "David", "StudentFriendName" : [ "Mike", "Sam", "James" ] } ] }
Advertisements