
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
Get Specific Elements from Embedded Array in MongoDB
To get specific elements, use $match with dot notation. Let us create a collection with documents −
> db.demo641.insert( ... { ... ProductId:101, ... "ProductInformation": ... ( [ ... { ... ProductName:"Product-1", ... "ProductPrice":1000 ... }, ... { ... ProductName:"Product-2", ... "ProductPrice":500 ... }, ... { ... ProductName:"Product-3", ... "ProductPrice":2000 ... }, ... { ... ProductName:"Product-4", ... "ProductPrice":3000 ... } ... ] ... } ... ); WriteResult({ "nInserted" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo641.find();
This will produce the following output −
{ "_id" : ObjectId("5e9c31d46c954c74be91e6e2"), "ProductId" : 101, "ProductInformation" : [ { "ProductName" : "Product-1", "ProductPrice" : 1000 }, { "ProductName" : "Product-2", "ProductPrice" : 500 }, { "ProductName" : "Product-3", "ProductPrice" : 2000 }, { "ProductName" : "Product-4", "ProductPrice" : 3000 } ] }
Following is the query to get specific elements from embedded array in MongoDB
> db.demo641.aggregate([ ... {$unwind: "$ProductInformation"}, ... {$match: { "ProductInformation.ProductPrice": {$in :[1000, 2000]}} }, ... {$project: {_id: 0, ProductInformation: 1} } ... ]).pretty();
This will produce the following output −
{ "ProductInformation" : { "ProductName" : "Product-1", "ProductPrice" : 1000 } } { "ProductInformation" : { "ProductName" : "Product-3", "ProductPrice" : 2000 } }
Advertisements