
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
Get Fields from Multiple Sub-Documents in MongoDB
To get fields from multiple sub-documents, use MongoDB aggregate with $unwind. Let us create a collection with documents −
> db.demo671.insertOne( ... { ... ... "details" : [ ... { ... "id" : "1" ... }, ... { ... CountryName:"US", ... "details1" : [ ... { ... "id" : "1" ... }, ... { ... "id" : "2" ... } ... ] ... }, ... { ... CountryName:"UK", ... "details1" : [ ... { ... "id" : "2" ... }, ... { ... "id" : "1" ... } ... ] ... }, ... { ... CountryName:"AUS", ... "details1" : [ ... { ... "id" : "1" ... } ... ] ... } ... ] ... } ... ) { "acknowledged" : true, "insertedId" : ObjectId("5ea3e5d004263e90dac943e0") }
Display all documents from a collection with the help of find() method −
> db.demo671.find();
This will produce the following output −
{ "_id" : ObjectId("5ea3e5d004263e90dac943e0"), "details" : [ { "id" : "1" }, { "CountryName" : "US", "details1" : [ { "id" : "1" }, { "id" : "2" } ] }, { "CountryName" : "UK", "details1" : [ { "id" : "2" }, { "id" : "1" } ] }, { "CountryName" : "AUS", "details1" : [ { "id" : "1" } ] } ] }
Here is the query to get fields from multiple sub-documents that match a condition in MongoDB −
> db.demo671.aggregate([ ... ... {$unwind: '$details'}, ... ... {$match: {'details.details1.id': '1'}}, ... ... {$project: {_id: 0, Country: '$details.CountryName'}} ... ]).pretty()
This will produce the following output −
{ "Country" : "US" } { "Country" : "UK" } { "Country" : "AUS" }
Advertisements