MongoDB query for fields in embedded document?

MongoDBDatabaseBig Data Analytics

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 } ] }
raja
Published on 22-May-2019 12:22:47
Advertisements