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

Projection: ดึงเฉพาะฟิลด์ Array ที่ต้องการใน MongoDB

ใช้ Projection (พารามิเตอร์ที่ 2 ของ find()) ร่วมกับ Dot Notation เพื่อระบุว่าให้คืนค่าเฉพาะฟิลด์ใน Array ที่ต้องการ ลด Bandwidth และเพิ่มประสิทธิภาพ

สร้างคอลเลกชันและข้อมูลตัวอย่าง

> db.projectionAnElementDemo.insertOne({
    "CustomerId": 100,
    "CustomerDetails": [
      {"CustomerName": "Chris", "CustomerCountryName": "US"},
      {"CustomerName": "Robert", "CustomerCountryName": "UK"}
    ]
  });
{ "acknowledged": true, "insertedId": ObjectId("5cd31c56b64f4b851c3a13ea") }

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

> db.projectionAnElementDemo.find().pretty();

ผลลัพธ์:

{
  "_id": ObjectId("5cd31c56b64f4b851c3a13ea"),
  "CustomerId": 100,
  "CustomerDetails": [
    {"CustomerName": "Chris", "CustomerCountryName": "US"},
    {"CustomerName": "Robert", "CustomerCountryName": "UK"}
  ]
}

Projection: ดึงเฉพาะ CustomerId และ CustomerName ใน Array

> db.projectionAnElementDemo.find(
  {},
  {CustomerId: 1, "CustomerDetails.CustomerName": 1}
).pretty();

ผลลัพธ์: CustomerCountryName ถูกซ่อน ไม่คืนค่า

{
  "_id": ObjectId("5cd31c56b64f4b851c3a13ea"),
  "CustomerId": 100,
  "CustomerDetails": [
    {"CustomerName": "Chris"},
    {"CustomerName": "Robert"}
  ]
}

กฎของ Projection

  • 1 = Include (รวม), 0 = Exclude (ตัดออก)
  • ไม่สามารถผสม Include และ Exclude ได้ (ยกเว้น _id: 0)
  • Dot Notation ใน Projection: "arrayField.nestedField": 1
  • คืนค่า Array ทั้งอัน แต่แต่ละ Element มีเฉพาะฟิลด์ที่ Include

ข้อจำกัด

  • Projection แบบนี้ ไม่สามารถกรอง Element ได้ (คืนทุก Element ใน Array)
  • หากต้องการกรอง Element: ใช้ Aggregation $project + $filter หรือ $map
  • หากต้องการคืน Element เดียวที่ตรงเงื่อนไข: ใช้ $elemMatch ใน Projection

ตัวอย่าง $elemMatch ใน Projection

// คืนเฉพาะ Element แรกที่ CustomerCountryName = "US"
db.projectionAnElementDemo.find(
  {},
  {CustomerId: 1, CustomerDetails: {$elemMatch: {CustomerCountryName: "US"}}}
);