How to get embedded data in a MongoDB document?


Following is the syntax to get the embedded data in a MongoDB document

db.yourCollectionName.find({},{‘yourOuterKeyName.yourInnerKeyName:1}).pretty();

Let us first create a collection with documents

> db.embeddedCollectionDemo.insertOne(
...    {
...       "StudentName" : "Larry",
...       "StudentDetails": {
...          "Larry1234": {"ProjectName": "Student Web Tracker"},
...          "Larry7645": {"ProjectName": "Hospital Management System"},
...          "Larry9879": {"ProjectName": "Library Management System"},
...
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c98a100330fd0aa0d2fe4c5")
}

Following is the query to display all documents from a collection

> db.embeddedCollectionDemo.find().pretty();

This will produce the following output

{
   "_id" : ObjectId("5c98a100330fd0aa0d2fe4c5"),
   "StudentName" : "Larry",
   "StudentDetails" : {
      "Larry1234" : {
         "ProjectName" : "Student Web Tracker"
      },
      "Larry7645" : {
         "ProjectName" : "Hospital Management System"
      },
      "Larry9879" : {
         "ProjectName" : "Library Management System"
      }
   }
}

Following is the query for embedded collections i.e. embedded data in MongoDB collection

> db.embeddedCollectionDemo.find({},{'StudentDetails.Larry7645':1}).pretty();

This will produce the following output

{
   "_id" : ObjectId("5c98a100330fd0aa0d2fe4c5"),
   "StudentDetails" : {
      "Larry7645" : {
         "ProjectName" : "Hospital Management System"
      }
   }
}

Updated on: 30-Jul-2019

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements