ใช้ Projection ใน find() ตัวที่สอง: ตั้งค่าฟิลด์ที่ต้องการเป็น 1 (แสดง), 0 (ซ่อน) _id ต้องตั้ง 0 โดยตรงถ้าไม่ต้องการ
ตัวอย่างข้อมูลทดสอบ
> db.demo384.insertOne({"StudentName":"Chris Brown","StudentCountryName":"US"});
> db.demo384.insertOne({"StudentName":"David Miller","StudentCountryName":"AUS"});
> db.demo384.insertOne({"StudentName":"John Doe","StudentCountryName":"UK"});
แสดงข้อมูลทั้งหมด
> db.demo384.find();
{
"_id" : ObjectId("5e5b67a022064be7ab44e7f2"),
"StudentName" : "Chris Brown", "StudentCountryName" : "US"
}
{
"_id" : ObjectId("5e5b67ab22064be7ab44e7f3"),
"StudentName" : "David Miller", "StudentCountryName" : "AUS"
}
{
"_id" : ObjectId("5e5b67b422064be7ab44e7f4"),
"StudentName" : "John Doe", "StudentCountryName" : "UK"
}
คิวรี่แสดงเฉพาะ StudentCountryName (ซ่อน _id และ StudentName)
> db.demo384.find({},{_id:0, StudentName:0});
ผลลัพธ์
{ "StudentCountryName" : "US" }
{ "StudentCountryName" : "AUS" }
{ "StudentCountryName" : "UK" }
กฎ Projection:
- ไม่สามารถผสม 0 และ 1 ได้ (ยกเว้น _id)
- การตั้ง
{_id:0, StudentCountryName:1}ก็ได้ผลเหมือนกัน - Projection ลด bandwidth และเพิ่มประสิทธิภาพ