- 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 query for fields in embedded document?
Let us first create a collection with documents −
> db.embeddedDocumentDemo.insertOne( ... { ... "CustomerDetails":[ ... {"CustomerName":"Chris", "CustomerPurchasePrice":3000}, ... {"CustomerName":"Robert", "CustomerPurchasePrice":4500}, ... {"CustomerName":"David", "CustomerPurchasePrice":1000}, ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd32347edc6604c74817ccd") }
Following is the query to display all documents from a collection with the help of find() method −
> db.embeddedDocumentDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd32347edc6604c74817ccd"), "CustomerDetails" : [ { "CustomerName" : "Chris", "CustomerPurchasePrice" : 3000 }, { "CustomerName" : "Robert", "CustomerPurchasePrice" : 4500 }, { "CustomerName" : "David", "CustomerPurchasePrice" : 1000 } ] }
Following is the query for embedded document −
> db.embeddedDocumentDemo.find({"CustomerDetails.CustomerPurchasePrice":4500});
This will produce the following output −
{ "_id" : ObjectId("5cd32347edc6604c74817ccd"), "CustomerDetails" : [ { "CustomerName" : "Chris", "CustomerPurchasePrice" : 3000 }, { "CustomerName" : "Robert", "CustomerPurchasePrice" : 4500 }, { "CustomerName" : "David", "CustomerPurchasePrice" : 1000 } ] }
Advertisements