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
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 } } }Advertisements