

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How to add new item in nested array with MongoDB?
For this, use find() along with update(). Let us create a collection with documents −
> db.demo124.insertOne( ... { ... "Name" : "John", ... "Id" : 101, ... "ProjectDetails" : [{ ... "ProjectName1" : "Online Book", ... "ProjectName2" : "Online Banking" ... }, { ... "ProjectName1" : "Online Library Management System", ... "ProjectName2" : "School Management System" ... }] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2f2c8b140daf4c2a3544bb") }
Display all documents from a collection with the help of find() method −
> db.demo124.find();
This will produce the following output −
{ "_id" : ObjectId("5e2f2c8b140daf4c2a3544bb"), "Name" : "John", "Id" : 101, "ProjectDetails" : [ { "ProjectName1" : "Online Book", "ProjectName2" : "Online Banking" }, { "ProjectName1" : "Online Library Management System", "ProjectName2" : "School Management System" } ] }
Following is the query to add new item in nested array −
> db.demo124.find().toArray().forEach( ... function(d){ ... for(var i = 0; i< d.ProjectDetails.length; ++i) { ... d.ProjectDetails[i]['ProjectName3'] = 'Online Snake Game'; ... } ... db.demo124.update({_id: d._id}, d); ... } ... );
Display all documents from a collection with the help of find() method −
> db.demo124.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e2f2c8b140daf4c2a3544bb"), "Name" : "John", "Id" : 101, "ProjectDetails" : [ { "ProjectName1" : "Online Book", "ProjectName2" : "Online Banking", "ProjectName3" : "Online Snake Game" }, { "ProjectName1" : "Online Library Management System", "ProjectName2" : "School Management System", "ProjectName3" : "Online Snake Game" } ] }
- Related Questions & Answers
- MongoDB query to add new array element in document
- MongoDB $addToSet to add a deep nested array of object?
- How to update a MongoDB document for adding a new item to an array?
- Query array of nested string with MongoDB?
- How to create double nested array in MongoDB?
- MongoDB $push in nested array?
- MongoDB query to aggregate nested array
- MongoDB query to sort nested array?
- Removing item from array in MongoDB?
- How to group nested fields in MongoDB aggregation with count value in array?
- MongoDB query to remove item from array?
- MongoDB query to gather unique array item?
- Query a nested field within an array with MongoDB
- Remove item from a nested array by indices in JavaScript
- MongoDB Increment value inside nested array?
Advertisements