Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

เข้าถึงค่า Sub-document ใน MongoDB เมื่อ Key เป็นตัวเลข (Numeric Key)

ใน MongoDB Key ของ Object สามารถเป็น String ที่เป็นตัวเลขได้ (เช่น "1", "2") การเข้าถึงต้องใช้ Bracket Notation ["key"] แทน Dot Notation

สร้างคอลเลกชันและข้อมูลตัวอย่าง (Key เป็น String ตัวเลข)

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

แสดงข้อมูล

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

เข้าถึง Sub-document ที่ Key = "1"

ใช้ Bracket Notation (Dot Notation .1 ไม่ได้ เพราะถูกตีความเป็น Array Index):

> db.accessSubDocumentDemo.findOne().Details["1"];

ผลลัพธ์:

{"StudentLowerScore": "33", "StudentHoghScore": "55"}

เหตุผลที่ต้องใช้ Bracket Notation

  • ใน JavaScript/MongoDB Shell: obj.1 เป็น Syntax Error
  • obj["1"] หรือ obj['1'] ถูกต้อง
  • Dot Notation ใช้ได้กับ Key ที่เป็น Valid Identifier (ขึ้นต้นตัวอักษร, _, $, ไม่มี Space)

การ Query ใน MongoDB (Server-side)

ใน Query ใช้ Dot Notation กับ String Key ได้ปกติ (MongoDB Parser จัดการ):

// หาเอกสารที่ Details.1.StudentLowerScore = "33"
db.accessSubDocumentDemo.find({"Details.1.StudentLowerScore": "33"});

// ใช้ $getField (Aggregation, MongoDB 5.0+)
db.accessSubDocumentDemo.aggregate([
  {$project: {score: {$getField: {field: "1", input: "$Details"}}}}
]);

Best Practice

  • หลีกเลี่ยง Numeric String Keys หากเป็นไปได้ ใช้ Key ที่เป็นคำอธิบาย (Descriptive)
  • หากต้องใช้ Array ของ Object: [{id: 1, ...}, {id: 2, ...}] แทน Object ที่ Key เป็นตัวเลข
  • Array ใช้ Index เข้าถึงได้: Details[0] (ใน Shell) หรือ Details.0 (ใน Query)