 
  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
How to retrieve all nested fields from MongoDB collection?
For this, use aggregate(). Let us create a collection with documents −
>db.demo138.insertOne({"Id":101,"PlayerDetails":[{"PlayerName":"Chris","PlayerScore":400},{"PlayerName":"David","PlayerScore":1000}]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e31bb9ffdf09dd6d08539a1") } >db.demo138.insertOne({"Id":102,"PlayerDetails":[{"PlayerName":"Bob","PlayerScore":500},{"PlayerName":"Carol","PlayerScore":600}]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e31bbcefdf09dd6d08539a2") } Display all documents from a collection with the help of find() method −
> db.demo138.find();
This will produce the following output −
{    "_id" : ObjectId("5e31bb9ffdf09dd6d08539a1"), "Id" : 101, "PlayerDetails" : [       { "PlayerName" : "Chris", "PlayerScore" : 400 },       { "PlayerName" : "David", "PlayerScore" : 1000 }    ] } {    "_id" : ObjectId("5e31bbcefdf09dd6d08539a2"), "Id" : 102, "PlayerDetails" : [       { "PlayerName" : "Bob", "PlayerScore" : 500 }, { "PlayerName" : "Carol", "PlayerScore" : 600 }    ] } Following is the query to retrieve all nested fields from the collection −
> db.demo138.aggregate([{ $unwind:"$PlayerDetails" }, { $project: { "PlayerName":"$PlayerDetails.PlayerName", "PlayerScore":"$PlayerDetails.PlayerScore" } } ] ); This will produce the following output −
{ "_id" : ObjectId("5e31bb9ffdf09dd6d08539a1"), "PlayerName" : "Chris", "PlayerScore" : 400 } { "_id" : ObjectId("5e31bb9ffdf09dd6d08539a1"), "PlayerName" : "David", "PlayerScore" : 1000 } { "_id" : ObjectId("5e31bbcefdf09dd6d08539a2"), "PlayerName" : "Bob", "PlayerScore" : 500 } { "_id" : ObjectId("5e31bbcefdf09dd6d08539a2"), "PlayerName" : "Carol", "PlayerScore" : 600 }Advertisements
 