- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Insert data into inner array in MongoDB?
You can use $addToSet operator for this. Let us first create a collection with documents −
> db.insertDataIntoArrayDemo.insertOne( { "UserDetails":[ { "UserId" :"user121", "userGroupMessage":[] }, { "UserId" :"user221", "userGroupMessage":["Cool","Good Morning"] } ] } ); { "acknowledged" : true, "insertedId" : ObjectId("5cd694e157806ebf1256f128") }
Following is the query to display all documents from a collection with the help of find() method −
> db.insertDataIntoArrayDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd694e157806ebf1256f128"), "UserDetails" : [ { "UserId" : "user121", "userGroupMessage" : [ ] }, { "UserId" : "user221", "userGroupMessage" : [ "Cool", "Good Morning" ] } ] }
Following is the query to insert data into inner array in MongoDB −
> db.insertDataIntoArrayDemo.update({"UserDetails.UserId":"user121"}, {"$addToSet":{"UserDetails.$.userGroupMessage":"Hello"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the document once again −
> db.insertDataIntoArrayDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd694e157806ebf1256f128"), "UserDetails" : [ { "UserId" : "user121", "userGroupMessage" : [ "Hello" ] }, { "UserId" : "user221", "userGroupMessage" : [ "Cool", "Good Morning" ] } ] }
Advertisements