How to access subdocument value when the key is a number in MongoDB?


To access subdocument value, let us first create a collection with documents −

> db.accessSubDocumentDemo.insertOne(
...    {
...
...       "Details" : {
...          "1" : {
...             "StudentLowerScore" : "33",
...             "StudentHoghScore" : "55"
...          },
...          "2" : {
...             "StudentLowerScore" : "45",
...             "StudentHoghScore" : "65"
...          },
...          "3" : {
...             "StudentLowerScore" : "39",
...             "StudentHoghScore" : "91"
...          },
...          "4" : {
...             "StudentLowerScore" : "41",
...             "StudentHoghScore" : "85"
...          }
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd3baf0edc6604c74817cd6")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cd3baf0edc6604c74817cd6"),
   "Details" : {
      "1" : {
         "StudentLowerScore" : "33",
         "StudentHoghScore" : "55"
      },
      "2" : {
         "StudentLowerScore" : "45",
         "StudentHoghScore" : "65"
      },
      "3" : {
         "StudentLowerScore" : "39",
         "StudentHoghScore" : "91"
      },
      "4" : {
         "StudentLowerScore" : "41",
         "StudentHoghScore" : "85"
      }
   }
}

Now, we will access subdocument value when the key is a number: Here, sub document is accessed for key with number 1 −

> db.accessSubDocumentDemo.findOne().Details["1"];

This will produce the following output −

{ "StudentLowerScore" : "33", "StudentHoghScore" : "55" }

Updated on: 30-Jul-2019

94 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements