當鍵為 MongoDB 中的數字時如何訪問子文件值?


為了訪問子文件值,我們先使用文件建立一個集合 −

> 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" }

更新時間: 2019 年 7 月 30 日

118 次瀏覽

開啟你的事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.