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 }

Updated on: 31-Mar-2020

687 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements