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
| Pattern | Syntax | หมายเหตุ |
|---|---|---|
| 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 |