Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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