![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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
How to insert an item to an array that is inside an object in MongoDB?
To insert an item to an already created array inside an object, use MongoDB $push. Let us create a collection with documents −
> db.demo449.insertOne( ... { ... details1: { ... details2: [{ ... _id:new ObjectId(), ... Name:"Chris" ... }], ... details3: [{ ... _id:new ObjectId(), ... Name:"David" ... }] ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e7a40e971f552a0ebb0a6e3") }
Display all documents from a collection with the help of find() method −
> db.demo449.find();
This will produce the following output −
{ "_id" : ObjectId("5e7a40e971f552a0ebb0a6e3"), "details1" : { "details2" : [ { "_id" : ObjectId("5e7a40e971f552a0ebb0a6e1"), "Name" : "Chris" } ], "details3" : [ { "_id" : ObjectId("5e7a40e971f552a0ebb0a6e2"), "Name" : "David" } ] } }
Following is the query to insert an item to an array that is inside an object −
> db.demo449.update({_id:ObjectId("5e7a40e971f552a0ebb0a6e3")}, {$push: { 'details1.details2':{_id:ObjectId(),"Name":"Carol"}}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }
Display all documents from a collection with the help of find() method −
> db.demo449.find();
This will produce the following output −
{ "_id" : ObjectId("5e7a40e971f552a0ebb0a6e3"), "details1" : { "details2" : [ { "_id" : ObjectId("5e7a40e971f552a0ebb0a6e1"), "Name" : "Chris" }, { "_id" : ObjectId("5e7a41a671f552a0ebb0a6e5"), "Name" : "Carol" } ], "details3" : [ { "_id" : ObjectId("5e7a40e971f552a0ebb0a6e2"), "Name" : "David" } ] } }
Advertisements