 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Query array of subdocuments in MongoDB
To query an array of subdocuments, use $unwind in MongoDB. Let us create a collection with documents −
> db.demo499.insertOne({ ... "details": ...    [ ...       { ...          Name :"MIT", ...          Rank: 1, ...          "CountryName":"US" ...       }, ... ...       { ...          Name :"Stanford University", ...          Rank: 2 ...       }, ... ...       { ...          Name :"University of California, Berkeley", ...          Rank: 3 ...       } ...    ] ... } ... ); {    "acknowledged" : true,    "insertedId" : ObjectId("5e87433d987b6e0e9d18f558") } Display all documents from a collection with the help of find() method −
> db.demo499.find();
This will produce the following output −
{ "_id" : ObjectId("5e87433d987b6e0e9d18f558"), "details" : [ { "Name" : "MIT", "Rank" : 1, "CountryName" : "US" }, { "Name" : "Stanford University", "Rank" : 2 }, { "Name" : "University of California, Berkeley", "Rank" : 3 } ] } Following is how to query an array of subdocuments −
> db.demo499.aggregate({$unwind: "$details"}, ... {$match: {"details.CountryName":{$exists: true}}}, ... {$project: {"details.Name": 1, "details.CountryName": 1, "_id": 0}}) This will produce the following output −
{ "details" : { "Name" : "MIT", "CountryName" : "US" } }Advertisements
 