
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
Fetch Records from Subdocument Array in MongoDB
To fetch records from a subdocument array, use $unwind along with $push. For ids beginning from 234, use regex in MongoDB.
Let us create a collection with documents −
> db.demo556.insertOne( ... { ... _id:101, ... details:[ ... { ... id:"234336", ... Name:"Chris" ... }, ... { ... id:"123456", ... Name:"Bob" ... }, ... { ... id:"234987", ... Name:"Carol" ... }, ... { ... id:"989768", ... Name:"David" ... }, ... { ... id:"234888", ... Name:"Sam" ... }, ... { ... id:"847656", ... Name:"John" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
Display all documents from a collection with the help of find() method −
> db.demo556.find();
This will produce the following output −
{ "_id" : 101, "details" : [ { "id" : "234336", "Name" : "Chris" }, { "id" : "123456", "Name" : "Bob" }, { "id" : "234987", "Name" : "Carol" }, { "id" : "989768", "Name" : "David" }, { "id" : "234888", "Name" : "Sam" }, { "id" : "847656", "Name" : "John" } ] }
Following is the query to fetch records from a subdocument array −
> db.demo556.aggregate({ ... $match: { ... "_id": 101 ... } ... }, { ... $unwind: "$details" ... }, { ... $match: { ... "details.id": { ... $regex: /^234/ ... } ... } ... }, { ... $group: { ... _id: "$_id", ... "Detail": { ... $push: "$details" ... } ... } ... }).pretty();
This will produce the following output −
{ "_id" : 101, "Detail" : [ { "id" : "234336", "Name" : "Chris" }, { "id" : "234987", "Name" : "Carol" }, { "id" : "234888", "Name" : "Sam" } ] }
Advertisements