- 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
MongoDB find() query for nested document?
To fetch a value from the nested document, use dot notation. Let us create a collection with documents −
> db.demo591.insert([ ... { "Name": "John", "Age": 23 }, ... {"Name": "Carol", "Age": 26}, ... { "Name": "Robert", "Age": 29, ... details:[ ... { ... Email:"Robert@gmail.com",CountryName:"US"},{"Post":35} ... ]} ... ]); BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 3, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })
Display all documents from a collection with the help of find() method −
> db.demo591.find();
This will produce the following output −
{ "_id" : ObjectId("5e92dd08fd2d90c177b5bcd3"), "Name" : "John", "Age" : 23 } { "_id" : ObjectId("5e92dd08fd2d90c177b5bcd4"), "Name" : "Carol", "Age" : 26 } { "_id" : ObjectId("5e92dd08fd2d90c177b5bcd5"), "Name" : "Robert", "Age" : 29, "details" : [ { "Email" : "Robert@gmail.com", "CountryName" : "US" }, { "Post" : 35 } ] }
Following is the query to fetch nested document using dot notation −
> db.demo591.find({"details.Email": "Robert@gmail.com"});
This will produce the following output −
{ "_id" : ObjectId("5e92dd08fd2d90c177b5bcd5"), "Name" : "Robert", "Age" : 29, "details" : [ { "Email" : "Robert@gmail.com", "CountryName" : "US" }, { "Post" : 35 } ] }
Advertisements