 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Make nested queries in MongoDB 4 to fetch a specific document
For nested queries, let us first create a collection with documents −
> db.demo492.insertOne({ ...    "ProductDetails" : ...    { ...       "StockDetails" : [ ...          { "ProductName" : "Product-1" }, ...          {"ProductName" : "Product-2"}, ...          { "ProductName" : "Product-3"} ... ...       ] ... ...    } ... }); {    "acknowledged" : true,    "insertedId" : ObjectId("5e849db8b0f3fa88e22790c2") } > > > > db.demo492.insertOne({ ...    "ProductDetails" : ...    { ...       "StockDetails" : [ ...          { "ProductName" : "Product-4" }, ...          {"ProductName" : "Product-5"}, ...          { "ProductName" : "Product-6"} ... ...       ] ... ...    } ... }); {    "acknowledged" : true,    "insertedId" : ObjectId("5e849dceb0f3fa88e22790c3") } Display all documents from a collection with the help of find() method −
> db.demo492.find();
This will produce the following output −
{ "_id" : ObjectId("5e849db8b0f3fa88e22790c2"), "ProductDetails" : { "StockDetails" : [ { "ProductName" : "Product-1" }, { "ProductName" : "Product-2" }, { "ProductName" : "Product3" } ] } } { "_id" : ObjectId("5e849dceb0f3fa88e22790c3"), "ProductDetails" : { "StockDetails" : [ { "ProductName" : "Product-4" }, { "ProductName" : "Product-5" }, { "ProductName" : "Product6" } ] } } Following displays nested queries in MongoDB using dot notation to fetch a specific document −
> db.demo492.find({ "ProductDetails.StockDetails.ProductName":"Product-1"}); This will produce the following output −
{ "_id" : ObjectId("5e849db8b0f3fa88e22790c2"), "ProductDetails" : { "StockDetails" : [ { "ProductName" : "Product-1" }, { "ProductName" : "Product-2" }, { "ProductName" : "Product3" } ] } }Advertisements
 