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

การเข้าถึง Child Element ใน MongoDB Collection ด้วย Key

MongoDB อนุญาตให้เข้าถึง Element ภายใน Object (Nested Document) โดยใช้ Dot Notation ร่วมกับ Key ได้ เนื้อหานี้สาธิตการ Query เอกสารที่ _id = 102 และดึงเฉพาะ Key details.0 (Element แรกของ Object details)

ตัวอย่างข้อมูลทดสอบ

> db.demo305.insertOne({
  _id: 101,
  FirstName : 'Chris',
  details : { "0":"102", "1":"10001" }
});
{ "acknowledged" : true, "insertedId" : 101 }

> db.demo305.insertOne({
  _id: 102,
  FirstName : 'David',
  details : { "0":"103", "1":"10002" }
});
{ "acknowledged" : true, "insertedId" : 102 }

แสดงข้อมูลทั้งหมด

> db.demo305.find();
{
  "_id" : 101,
  "FirstName" : "Chris",
  "details" : { "0" : "102", "1" : "10001" }
}
{
  "_id" : 102,
  "FirstName" : "David",
  "details" : { "0" : "103", "1" : "10002" }
}

Query ดึง Child Element โดย Key

> db.demo305.find({_id:102}, {'details.0':1});

ผลลัพธ์

{
  "_id" : 102,
  "details" : { "0" : "103" }
}

คำอธิบาย

  • Filter: {_id:102} เลือกเอกสารที่ _id = 102
  • Projection: {'details.0':1} ระบุว่า Include เฉพาะ Key "0" ภายใน Object details
  • Dot Notation ใช้เข้าถึง Key ของ Embedded Document ได้ (details.0)
  • _id จะถูก Include เสมอ ถ้าไม่ต้องการต้องระบุ _id:0 ชัดเจน
  • วิธีนี้ใช้ได้กับ Object/Sub-document ไม่ใช่ Array (Array ใช้ Index ตรงๆ เช่น array.0)