Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to access subdocument value when the key is a number in MongoDB?
To access subdocument values when the key is a number in MongoDB, use bracket notation with quotes around the numeric key. This is necessary because numeric keys are stored as strings in MongoDB subdocuments.
Syntax
db.collection.findOne().fieldName["numericKey"]
db.collection.find({"fieldName.numericKey.subfield": value})
Sample Data
db.accessSubDocumentDemo.insertOne({
"Details": {
"1": {
"StudentLowerScore": "33",
"StudentHighScore": "55"
},
"2": {
"StudentLowerScore": "45",
"StudentHighScore": "65"
},
"3": {
"StudentLowerScore": "39",
"StudentHighScore": "91"
},
"4": {
"StudentLowerScore": "41",
"StudentHighScore": "85"
}
}
});
{
"acknowledged": true,
"insertedId": ObjectId("5cd3baf0edc6604c74817cd6")
}
Example 1: Access Specific Subdocument
To access the subdocument with key "1" ?
db.accessSubDocumentDemo.findOne().Details["1"];
{ "StudentLowerScore": "33", "StudentHighScore": "55" }
Example 2: Query Using Dot Notation
To find documents where student "2" has a high score of "65" ?
db.accessSubDocumentDemo.find({"Details.2.StudentHighScore": "65"});
{
"_id": ObjectId("5cd3baf0edc6604c74817cd6"),
"Details": {
"1": { "StudentLowerScore": "33", "StudentHighScore": "55" },
"2": { "StudentLowerScore": "45", "StudentHighScore": "65" },
"3": { "StudentLowerScore": "39", "StudentHighScore": "91" },
"4": { "StudentLowerScore": "41", "StudentHighScore": "85" }
}
}
Key Points
- Use bracket notation with quotes for numeric keys:
["1"] - In dot notation queries, numeric keys can be used directly:
"Details.1.field" - Always treat numeric keys as strings when accessing subdocuments
Conclusion
Access subdocuments with numeric keys using bracket notation with quotes. This approach works both for direct access and within query conditions using dot notation.
Advertisements
