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