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

วิธีซ่อน _id จากผลลัพธ์ Query ใน MongoDB (Projection)

ใช้ Projection ใน find() ระบุ { _id: 0 } เพื่อ exclude _id ออกจากผลลัพธ์

รูปแบบคำสั่ง

db.collection.find({}, { _id: 0 });

ตัวอย่างเต็มรูปแบบ

1. สร้างข้อมูลตัวอย่าง

> db.removeIdDemo.insertOne({"UserName":"John","UserAge":23});
> db.removeIdDemo.insertOne({"UserName":"Mike","UserAge":27});
> db.removeIdDemo.insertOne({"UserName":"Sam","UserAge":34});
> db.removeIdDemo.insertOne({"UserName":"Carol","UserAge":29});

2. แสดงข้อมูลปกติ (มี _id)

> db.removeIdDemo.find().pretty();
{ "_id" : ObjectId("..."), "UserName" : "John", "UserAge" : 23 }
{ "_id" : ObjectId("..."), "UserName" : "Mike", "UserAge" : 27 }
{ "_id" : ObjectId("..."), "UserName" : "Sam", "UserAge" : 34 }
{ "_id" : ObjectId("..."), "UserName" : "Carol", "UserAge" : 29 }

3. ซ่อน _id (Projection: { _id: 0 })

> db.removeIdDemo.find({}, { _id: 0 });
{ "UserName" : "John", "UserAge" : 23 }
{ "UserName" : "Mike", "UserAge" : 27 }
{ "UserName" : "Sam", "UserAge" : 34 }
{ "UserName" : "Carol", "UserAge" : 29 }

Projection Patterns

Projectionผลลัพธ์
{} หรือ ไม่ระบุInclude ทุกฟิลด์ (รวม _id)
{ _id: 0 }Exclude _id, Include อื่นๆ ทั้งหมด
{ field1: 1, field2: 1 }Include field1, field2, _id
{ field1: 1, _id: 0 }Include field1, Exclude _id

กรณีใช้งาน

  • API Response: ไม่ต้องการ expose internal _id
  • Data Export: Export เฉพาะ business fields
  • Performance: ลดขนาด Network Transfer
  • Security: ซ่อน ObjectId structure

สรุป

  • ใช้ find({}, { _id: 0 }) เพื่อซ่อน _id
  • _id เป็นฟิลด์เดียวที่สามารถ exclude ได้พร้อม include ฟิลด์อื่น
  • Projection ไม่เปลี่ยนข้อมูลใน Database แค่ควบคุมผลลัพธ์ที่ส่งกลับ
  • ใช้ได้กับ find(), findOne(), aggregate() ($project)