MongoDB View คือ read-only virtual collection ที่สร้างจาก aggregation pipeline บน source collection ข้อมูลไม่ถูกเก็บซ้ำ แสดงผลล่าสุดเสมอเมื่อ query
สร้างคอลเลกชันและข้อมูลตัวอย่าง
> db.demo113.insertOne({
_id: 1, StudentId: "101",
"Details": { Name: "Chris", Age: 21 },
Subject: "MySQL"
});
{ "acknowledged" : true, "insertedId" : 1 }
แสดงข้อมูล Source Collection
> db.demo113.find().pretty();
ผลลัพธ์:
{ "_id" : 1, "StudentId" : "101", "Details" : { "Name" : "Chris", "Age" : 21 }, "Subject" : "MySQL" }
Query สร้าง View
> db.createView(
"firstView",
"demo113",
[ { $project: { "Name": "$Details.Name", Subject: 1 } } ]
)
{ "ok" : 1 }
คำอธิบาย:
"firstView": ชื่อ view"demo113": source collection[{$project: {...}}]: aggregation pipeline กำหนดรูปแบบ view"Name": "$Details.Name": ดึง nested field มาเป็น top-level
Query ข้อมูลจาก View
> db.firstView.find();
ผลลัพธ์:
{ "_id" : 1, "Subject" : "MySQL", "Name" : "Chris" }
คุณสมบัติของ View
- Read-only: ไม่สามารถ insert/update/delete ได้
- Real-time: ข้อมูลใน view อัปเดตอัตโนมัติเมื่อ source collection เปลี่ยน
- No storage: ไม่ใช้พื้นที่เก็บข้อมูลเพิ่ม (เก็บแค่ definition)
- Security: ให้สิทธิ์เข้าถึง view แทน collection จริง (field-level security)
- Index: ใช้ index ของ source collection
จัดการ View
// ดู view ทั้งหมด
db.getCollectionInfos({type: "view"})
// ลบ view
db.firstView.drop()
// แก้ไข view (ต้อง drop แล้วสร้างใหม่)
db.firstView.drop()
db.createView("firstView", "demo113", [...new pipeline...])
View พร้อม $lookup (Join)
db.createView("studentWithCourses", "students", [
{ $lookup: {
from: "courses",
localField: "courseIds",
foreignField: "_id",
as: "courses"
}},
{ $project: { name: 1, "courses.title": 1 }}
])
ข้อจำกัด
- ไม่รองรับ $out, $merge, $geoNear
- ไม่สามารถสร้าง index บน view โดยตรง
- Collation ใช้ของ source collection
- Sharded collection: view ต้องอยู่ database เดียวกัน
สรุป: View เหมาะสำหรับ简化 complex queries, security (hide sensitive fields), และ reusable pipelines