- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Return specific MongoDB embedded document
Use $unwind twice for specific embedded document in MongoDB. Let us create a collection with documents −
> db.demo631.insert( ... { ... id: "101", ... Info1: [ ... { ... CountryName : "US", ... Info2 : [ ... { ... Name:"Chris", ... Age:24 ... },{ ... ... Name:"Bob", .. . Age:22 ... } ... ] ... } ... ] ... } ... ); WriteResult({ "nInserted" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo631.find();
This will produce the following output −
{ "_id" : ObjectId("5e9b0eb16c954c74be91e6bf"), "id" : "101", "Info1" : [ { "CountryName" : "US", "Info2" : [ { "Name" : "Chris", "Age" : 24 }, { "Name" : "Bob", "Age" : 22 } ] } ] }
Following is the query to return specific MongoDB embedded document −
> db.demo631.aggregate([ ... { "$unwind": "$Info1" }, ... { "$unwind": "$Info1.Info2" }, ... { "$match": { "Info1.Info2.Age": 22 } } ... ])
This will produce the following output −
{ "_id" : ObjectId("5e9b0eb16c954c74be91e6bf"), "id" : "101", "Info1" : { "CountryName" : "US", "Info2" : { "Name" : "Bob", "Age" : 22 } } }
- Related Articles
- MongoDB query to return only embedded document?
- MongoDB query for fields in embedded document?
- Implement MongoDB $push in embedded document array?
- How to get embedded data in a MongoDB document?
- Increment a field in MongoDB document which is embedded?
- Filter query on array of embedded document with MongoDB?
- Get specific elements from embedded array in MongoDB?
- How to find a certain element in the MongoDB embedded document?
- MongoDB query to remove a specific document
- Filter specific values from a MongoDB document
- Add a field to an embedded document in an array in MongoDB?
- MongoDB - How to check for equality in collection and in embedded document?
- Extract a MongoDB document with a specific string
- Find which MongoDB document contains a specific string?
- Return a specific field in MongoDB?

Advertisements