- 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 do I access subdocuments in MongoDB queries?
To access subdocuments in MongoDB, use find() with dot notation. Let us create a collection with documents −
> db.demo670.insertOne({ ... id:101, ... "details": ... { ... Name:"Chris", ... Age:21, ... CountryName:"US", ... SubjectName:"MongoDB" ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ea3e31d04263e90dac943de") } > db.demo670.insertOne({ id:102, "details": { Name:"David", Age:22, CountryName:"UK", SubjectName:"MySQL" } } ); { "acknowledged" : true, "insertedId" : ObjectId("5ea3e33604263e90dac943df") }
Display all documents from a collection with the help of find() method −
> db.demo670.find();
This will produce the following output −
{ "_id" : ObjectId("5ea3e31d04263e90dac943de"), "id" : 101, "details" : { "Name" : "Chris", "Age" : 21, "CountryName" : "US", "SubjectName" : "MongoDB" } } { "_id" : ObjectId("5ea3e33604263e90dac943df"), "id" : 102, "details" : { "Name" : "David", "Age" : 22, "CountryName" : "UK", "SubjectName" : "MySQL" } }
Following is the query to access subdocuments −
> db.demo670.find({"details.SubjectName":"MongoDB"},{"details.CountryName":1});7
This will produce the following output −
{ "_id" : ObjectId("5ea3e31d04263e90dac943de"), "details" : { "CountryName" : "US" } }
Advertisements