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 } ] }

Updated on: 30-Jul-2019

161 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements