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" } ] } }
Updated on: 2020-05-13T05:27:50+05:30

494 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements