Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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 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" }Advertisements