

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 a subdocument array wherein id begins from 234 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" } ] }
- Related Questions & Answers
- Fetch similar ID records from two tables in MySQL
- MongoDB query to remove subdocument from document?
- MySQL query to fetch records wherein timestamp is before 15+ days?
- Fetch unique records from table in SAP ABAP
- MySQL query to select records beginning from a specific id
- MySQL query to fetch records from a range of months?
- Fetch records from comma separated values using MySQL IN()?
- MySQL query to fetch specific records matched from an array (comma separated values)
- How to fetch the newly added records from a MySQL table?
- Fetch alternative even values from a JavaScript array?
- Exclude some ID records from a list and display rest in MySQL
- Match ID and fetch documents with $eq in MongoDB in case of array?
- How to filter array in subdocument with MongoDB?
- Fetch records from interval of past 3 days from current date in MySQL and add the corresponding records
- PHP fetch a specific value that begins with a given number from a string with letters and numbers?
Advertisements