
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Retrieve Nested Object in MongoDB
To retrieve a nested object in MongoDB, use $ operator. Let us first create a collection with documents −
> db.queryNestedObject.insertOne( ... { ... "StudentName" : "James", ... "StudentSubjectScore" : [ ... {"StudentMongoDBScore":98}, ... {"StudentCScore":92}, ... {"StudentJavaScore":91} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ccf49a9dceb9a92e6aa1962") }
Following is the query to display all documents from a collection with the help of find() method −
> db.queryNestedObject.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5ccf49a9dceb9a92e6aa1962"), "StudentName" : "James", "StudentSubjectScore" : [ { "StudentMongoDBScore" : 98 }, { "StudentCScore" : 92 }, { "StudentJavaScore" : 91 } ] }
Following is the query to retrieve a nested object −
> db.queryNestedObject.find({'StudentSubjectScore.StudentJavaScore' : 91},{'StudentSubjectScore.$': 1 , _id: 0});
This will produce the following output −
{ "StudentSubjectScore" : [ { "StudentJavaScore" : 91 } ] }
Advertisements