- 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
Query deeply nested Objects in MongoDB
To query deeply nested objects, use dot(.) notation in MongoDB. Let us create a collection with documents −
> db.demo350.insertOne( ... { ... id:101, ... Name: "Chris", ... details: [ ... { ... _id: 1, ... ClientNumber: "10001", ... ClientDetails: [ . ... { ... Name:"David", ... Age:29 ... }, ... { ... Name:"Bob", ... Age:31 ... } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e553a68f8647eb59e5620b8") } > db.demo350.insertOne( ... { ... id:102, ... Name: "David", ... details: [ ... { ... _id: 2, ... ClientNumber: "10002", ... ClientDetails: [ ... { ... Name:"Carol", ... Age:42 ... }, ... { ... Name:"John", ... Age:37 ... } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e553a8ff8647eb59e5620b9") }
Display all documents from a collection with the help of find() method −
> db.demo350.find();
This will produce the following output −
{ "_id" : ObjectId("5e553a68f8647eb59e5620b8"), "id" : 101, "Name" : "Chris", "details" : [ { "_id" : 1, "ClientNumber" : "10001", "ClientDetails" : [ { "Name" : "David", "Age" : 29 }, { "Name" : "Bob", "Age" : 31 } ] } ] } { "_id" : ObjectId("5e553a8ff8647eb59e5620b9"), "id" : 102, "Name" : "David", "details" : [ { "_id" : 2, "ClientNumber" : "10002", "ClientDetails" : [ { "Name" : "Carol", "Age" : 42 }, { "Name" : "John", "Age" : 37 } ] } ] }
Following is how to query deeply nested objects −
> db.demo350.find({"details.ClientDetails.Name":"John"});
This will produce the following output −
{ "_id" : ObjectId("5e553a8ff8647eb59e5620b9"), "id" : 102, "Name" : "David", "details" : [ { "_id" : 2, "ClientNumber" : "10002", "ClientDetails" : [ { "Name" : "Carol", "Age" : 42 }, { "Name" : "John", "Age" : 37 } ] } ] }
Advertisements