- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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" ] } ] }
- Related Articles
- How to sort inner array in MongoDB?
- Accessing inner element of JSON array in MongoDB?
- Check duplicates of certain field for inner array in MongoDB
- Insert to specific index for MongoDB array?
- Array index or indexing inner items in MongoDB to fetch values
- How to insert data into a CachedRowSet in JDBC? Explain?
- How can we insert data into a MySQL table?
- Using EF to insert data into SAP Business One.
- How to insert new documents into a MongoDB collection in your database?
- Is there any way in MongoDB to get the inner value of json data?
- How to insert a document into a MongoDB collection using Java?
- How to insert multiple document into a MongoDB collection using Java?
- How to insert Binary data into a table using JDBC?
- How to insert data into a MySQL database with Java?
- MongoDB query to insert an array element with a condition?

Advertisements