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

MongoDB Projection: ดึง Column เดียว (Single Field Projection)

Projection ใน MongoDB ใช้ควบคุม field ที่คืนค่าใน query result ใช้ 1 (include) หรือ 0 (exclude) ไม่สามารถผสม include/exclude ได้ (ยกเว้น _id)

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

> db.demo216.insertOne({"ClientName":"John","ClientAge":34});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3e351003d395bdc213470c") }
> db.demo216.insertOne({"ClientName":"Bob","ClientAge":32});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3e351703d395bdc213470d") }
> db.demo216.insertOne({"ClientName":"Mike","ClientAge":35});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3e351c03d395bdc213470e") }

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

> db.demo216.find();

ผลลัพธ์: _id, ClientName, ClientAge

Query Projection: ดึงเฉพาะ ClientName (exclude _id, ClientAge)

> db.demo216.find({}, {_id: 0, "ClientAge": 0});

คำอธิบาย:

  • Filter: {} (ทุกเอกสาร)
  • Projection: {_id: 0, "ClientAge": 0} - exclude _id และ ClientAge
  • Field ที่ไม่ระบุ (ClientName) จะถูก include อัตโนมัติ

ผลลัพธ์

{ "ClientName" : "John" }
{ "ClientName" : "Bob" }
{ "ClientName" : "Mike" }

Projection Patterns

ข้อจำกัด: ไม่สามารถผสม Include/Exclude ได้

// ผิด - จะ error
{ClientName: 1, ClientAge: 0}

// ถูก - เลือกแบบใดแบบหนึ่ง
{ClientName: 1, _id: 0}           // Include mode
{ClientAge: 0, _id: 0}             // Exclude mode

Projection ใน Aggregate ($project)

ยืดหยุ่นกว่า: rename, compute, conditional

db.demo216.aggregate([
  { $project: {
    name: "$ClientName",           // rename
    age: "$ClientAge",
    isAdult: { $gte: ["$ClientAge", 18] },  // computed
    _id: 0
  }}
])
// { name: "John", age: 34, isAdult: true }

Performance: Covered Queries

หาก query ใช้ index และ projection รวม field ใน index เท่านั้น → Covered Query (อ่านจาก index โดยไม่ต้อง fetch document)

// สร้าง index
db.demo216.createIndex({ClientName: 1})

// Query นี้เป็น covered query (ใช้ index only)
db.demo216.find({}, {ClientName: 1, _id: 0})

สรุป: Projection ลด network transfer และ memory usage ใช้ exclude mode ({field: 0}) สำหรับตัด field น้อยๆ | include mode สำหรับดึง field เล็กน้อย

PatternSyntaxหมายเหตุ
Include specific fields{field1: 1, field2: 1}_id included by default
Exclude specific fields{field1: 0, field2: 0}อื่นๆ included, _id ต้องระบุ 0 แยก
Include nested field{"address.city": 1}Dot notation
Exclude nested field{"address.city": 0}
Array element (positional){"array.$": 1}ต้องมี filter match array
Slice array{array: {$slice: 5}}5 elements แรก
Array filter ($elemMatch){array: {$elemMatch: {cond}}}Return matching element only