![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 only get the data of the nested JSON object in MongoDB?
To get the data of the nested JSON object in MongoDB, use findOne(). Let us create a collection with documents −
> db.demo109.insertOne( ... { ... "Name" : "Chris", ... "Subjects" : [ ... { ... "Id" : "100", ... "Name":"MySQL", ... "InstructorDetails" : [ ... { ... "Name" : "John" ... } ... ] ... }, ... { ... "Id" : "101", ... "Name":"MongoDB", ... "InstructorDetails" : [ ... { ... "Name" : "Mike" ... } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2ee7df9fd5fd66da21447a") }
Display all documents from a collection with the help of find() method −
> db.demo109.find();
This will produce the following output −
{ "_id" : ObjectId("5e2ee7df9fd5fd66da21447a"), "Name" : "Chris", "Subjects" : [ { "Id" : "100", "Name" : "MySQL", "InstructorDetails" : [ { "Name" : "John" } ] }, { "Id" : "101", "Name" : "MongoDB", "InstructorDetails" : [ { "Name" : "Mike" } ] } ] }
Following is the query to only get the data of the nested JSON object in MongoDB −
> db.demo109.findOne( ... { Name: "Chris"} ... , { 'Subjects': { $elemMatch:{'Id':"100"} } } ... , function (err, doc) { console.log(doc) });
This will produce the following output −
{ "_id" : ObjectId("5e2ee7df9fd5fd66da21447a"), "Subjects" : [ { "Id" : "100", "Name" : "MySQL", "InstructorDetails" : [ { "Name" : "John" } ] } ] }
Advertisements