How to get a specific object from array of objects inside specific MongoDB document?


To get specific object from array of objects, use positional operator($). Let us first create a collection with documents −

> db.getASpecificObjectDemo.insertOne(
...   {
...      _id :1,f
...      "CustomerName" : "Larry",
...      "CustomerDetails" : {
...         "CustomerPurchaseDescription": [{
...            id :100,
...            "ProductName" : "Product-1",
...            "Amount":10000
...         },{
...               id :101,
...               "ProductName" : "Product-2",
...               "Amount":10500
...            },
...            {
...               id :102,
...               "ProductName" : "Product-3",
...               "Amount":10200
...            }
...         ]
...      }
...  }
... );
{ "acknowledged" : true, "insertedId" : 1 }

Following is the query to display all documents from a collection with the help of find() method −

> db.getASpecificObjectDemo.find().pretty();

This will produce the following output −

{
   "_id" : 1,
   "CustomerName" : "Larry",
   "CustomerDetails" : {
      "CustomerPurchaseDescription" : [
           {
             "id" : 100,
             "ProductName" : "Product-1",
             "Amount" : 10000
           },
           {
             "id" : 101,
             "ProductName" : "Product-2",
             "Amount" : 10500
           },
           {
             "id" : 102,
             "ProductName" : "Product-3",
             "Amount" : 10200
           }
      ]
   }
}

Following is the query to get a specific object from array of objects inside specific MongoDB document −

> db.getASpecificObjectDemo.find({_id:1, "CustomerDetails.CustomerPurchaseDescription.id":101},{_id:0, "CustomerDetails.CustomerPurchaseDescription.$":1});

This will produce the following output −

{ "CustomerDetails" : { "CustomerPurchaseDescription" : [ { "id" : 101, "ProductName" : "Product-2", "Amount" : 10500 } ] } }

Updated on: 30-Jul-2019

336 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements