- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract subarray value in MongoDB?
To extract the subarray value in MongoDB, you can use $elemMatch projection operator.
Let us first create a collection with documents −
> db.extractSubArrayDemo.insertOne( ... { ... _id: 101, ... "clientName":"Larry", ... "ClientDetails": ... [ ... { ... "ClientProjectName":"Online Game", ... "DeveloperTeamSize": 10 ... }, ... { ... "ClientProjectName":"Pig Dice Game", ... "DeveloperTeamSize": 12 ... }, ... { ... "ClientProjectName":"Web Student Tracker", ... "DeveloperTeamSize": 11 ... } ... ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
Following is the query to display all documents from the collection with the help of find() method −
> db.extractSubArrayDemo.find().pretty();
This will produce the following output −
{ "_id" : 101, "clientName" : "Larry", "ClientDetails" : [ { "ClientProjectName" : "Online Game", "DeveloperTeamSize" : 10 }, { "ClientProjectName" : "Pig Dice Game", "DeveloperTeamSize" : 12 }, { "ClientProjectName" : "Web Student Tracker", "DeveloperTeamSize" : 11 } ] }
Following is the query to extract subarray value in MongoDB −
> db.extractSubArrayDemo.find({ '_id': 101 },{ _id: 0, ClientDetails: { $elemMatch: {ClientProjectName: 'Pig Dice Game' } }}).pretty();
This will produce the following output −
{ "ClientDetails" : [ { "ClientProjectName" : "Pig Dice Game", "DeveloperTeamSize" : 12 } ] }
Advertisements