하위 문서 값에 액세스하려면 먼저 문서가 포함된 컬렉션을 만듭니다.
> 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" }