Access objects from the nested objects structure in MongoDB


Access objects using dot notation. Let us first create a collection with documents

> db.nestedObjectDemo.insertOne({"Student" : { "StudentDetails" : { "StudentPersonalDetails" : { "StudentName" : [ "John" ],
... "StudentCountryName" : [ "US" ],
... "StudentCoreSubject" : [ "C", "Java" ],
... "StudentProject" : [ "Online Book Store", "Pig Dice Game" ] } } } });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c99dfc2863d6ffd454bb650")
}

Following is the query to display all documents from a collection with the help of find() method

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

This will produce the following output

{
   "_id" : ObjectId("5c99dfc2863d6ffd454bb650"),
   "Student" : {
      "StudentDetails" : {
         "StudentPersonalDetails" : {
            "StudentName" : [
               "John"
            ],
            "StudentCountryName" : [
               "US"
            ],
            "StudentCoreSubject" : [
               "C",
               "Java"
            ],
            "StudentProject" : [
               "Online Book Store",
               "Pig Dice Game"
            ]
         }
      }
   }
}

Following is the query to access nested objects using dot notation

>db.nestedObjectDemo.find({"Student.StudentDetails.StudentPersonalDetails.StudentName":"John"}).pretty();

This will produce the following output

{
   "_id" : ObjectId("5c99dfc2863d6ffd454bb650"),
   "Student" : {
      "StudentDetails" : {
         "StudentPersonalDetails" : {
            "StudentName" : [
               "John"
            ],
            "StudentCountryName" : [
               "US"
            ],
            "StudentCoreSubject" : [
               "C",
               "Java"
            ],
            "StudentProject" : [
               "Online Book Store",
               "Pig Dice Game"
            ]
         }
      }
   }
}

Updated on: 30-Jul-2019

581 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements