ในการเข้าถึงค่าเอกสารย่อย ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน -
> 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")
} ต่อไปนี้เป็นแบบสอบถามเพื่อแสดงเอกสารทั้งหมดจากคอลเลกชันโดยใช้วิธี find() -
> db.accessSubDocumentDemo.find().pretty();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{
"_id" : ObjectId("5cd3baf0edc6604c74817cd6"),
"Details" : {
"1" : {
"StudentLowerScore" : "33",
"StudentHoghScore" : "55"
},
"2" : {
"StudentLowerScore" : "45",
"StudentHoghScore" : "65"
},
"3" : {
"StudentLowerScore" : "39",
"StudentHoghScore" : "91"
},
"4" : {
"StudentLowerScore" : "41",
"StudentHoghScore" : "85"
}
}
} ตอนนี้ เราจะเข้าถึงค่าเอกสารย่อยเมื่อคีย์เป็นตัวเลข:ที่นี่ เข้าถึงเอกสารย่อยสำหรับคีย์ที่มีหมายเลข 1 -
> db.accessSubDocumentDemo.findOne().Details["1"];
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "StudentLowerScore" : "33", "StudentHoghScore" : "55" }