- 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
Extract a particular element from a nested array in MongoDB
Extract a particular element from a nested array with the help of dot(.) notation. Let us first create a collection with documents −
> db.extractParticularElementDemo.insertOne( ... { ... "_id" : 101, ... "StudentName" : "John", ... "StudentInformation" : [ ... { ... "Age" : 21, ... "StudentPersonalInformation" : [ ... { ... "StudentNickName" : "Mike", ... "StudentFamilyDetails" : [ ... { ... "FatherName" : "Carol" ... } ... ] ... }, ... { ... "StudentAnotherName" : "David", ... "StudentFamilyDetails" : [ ... { ... "FatherName" : "Robert" ... } ... ] ... } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
Following is the query to display all documents from a collection with the help of find() method −
> db.extractParticularElementDemo.find().pretty();
This will produce the following output −
{ "_id" : 101, "StudentName" : "John", "StudentInformation" : [ { "Age" : 21, "StudentPersonalInformation" : [ { "StudentNickName" : "Mike", "StudentFamilyDetails" : [ { "FatherName" : "Carol" } ] }, { "StudentAnotherName" : "David", "StudentFamilyDetails" : [ { "FatherName" : "Robert" } ] } ] } ] }
Following is the query to extract particular element from a nested array −
> db.extractParticularElementDemo.find( ... {'StudentInformation.StudentPersonalInformation.StudentFamilyDetails.FatherName':'Carol'}, ... {'StudentInformation.StudentPersonalInformation.StudentFamilyDetails.FatherName':1,"_id":0} ... ).pretty();
This will produce the following output −
{ "StudentInformation" : [ { "StudentPersonalInformation" : [ { "StudentFamilyDetails" : [ { } "FatherName" : "Carol" ] }, { "StudentFamilyDetails" : [ { "FatherName" : "Robert" } ] } ] } ] }
Advertisements