- 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
Access objects from the nested objects structure in MongoDB
Access objects using dot notation. Let us first create a collection with documents
> db.nestedObjectDemo.insertOne({"Student" : { "StudentDetails" : { "StudentPersonalDetails" : { "StudentName" : [ "John" ], ... "StudentCountryName" : [ "US" ], ... "StudentCoreSubject" : [ "C", "Java" ], ... "StudentProject" : [ "Online Book Store", "Pig Dice Game" ] } } } }); { "acknowledged" : true, "insertedId" : ObjectId("5c99dfc2863d6ffd454bb650") }
Following is the query to display all documents from a collection with the help of find() method
> db.nestedObjectDemo.find().pretty();
This will produce the following output
{ "_id" : ObjectId("5c99dfc2863d6ffd454bb650"), "Student" : { "StudentDetails" : { "StudentPersonalDetails" : { "StudentName" : [ "John" ], "StudentCountryName" : [ "US" ], "StudentCoreSubject" : [ "C", "Java" ], "StudentProject" : [ "Online Book Store", "Pig Dice Game" ] } } } }
Following is the query to access nested objects using dot notation
>db.nestedObjectDemo.find({"Student.StudentDetails.StudentPersonalDetails.StudentName":"John"}).pretty();
This will produce the following output
{ "_id" : ObjectId("5c99dfc2863d6ffd454bb650"), "Student" : { "StudentDetails" : { "StudentPersonalDetails" : { "StudentName" : [ "John" ], "StudentCountryName" : [ "US" ], "StudentCoreSubject" : [ "C", "Java" ], "StudentProject" : [ "Online Book Store", "Pig Dice Game" ] } } } }
Advertisements