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

วิธีดึงเฉพาะฟิลด์ _id ใน MongoDB (Projection)

ใช้ Projection (พารามิเตอร์ที่ 2 ของ find) ระบุ { "_id": 1 } เพื่อดึงเฉพาะฟิลด์ _id

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

db.collection.find({}, { "_id": 1 }).pretty();
  • {} = Query filter (ว่าง = ทุกเอกสาร)
  • { "_id": 1 } = Include เฉพาะ _id (0 = exclude)

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

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

> db.singlePropertyIdDemo.insertOne({"_id":101,"UserName":"Larry","UserAge":21});
> db.singlePropertyIdDemo.insertOne({"_id":102,"UserName":"Mike","UserAge":26});
> db.singlePropertyIdDemo.insertOne({"_id":103,"UserName":"Chris","UserAge":24});
> db.singlePropertyIdDemo.insertOne({"_id":104,"UserName":"Robert","UserAge":23});
> db.singlePropertyIdDemo.insertOne({"_id":105,"UserName":"John","UserAge":27});

2. แสดงข้อมูลทั้งหมด (ไม่มี projection)

> db.singlePropertyIdDemo.find().pretty();
{ "_id" : 101, "UserName" : "Larry", "UserAge" : 21 }
{ "_id" : 102, "UserName" : "Mike", "UserAge" : 26 }
{ "_id" : 103, "UserName" : "Chris", "UserAge" : 24 }
{ "_id" : 104, "UserName" : "Robert", "UserAge" : 23 }
{ "_id" : 105, "UserName" : "John", "UserAge" : 27 }

3. ดึงเฉพาะ _id

> db.singlePropertyIdDemo.find({}, { "_id": 1 }).pretty();
{ "_id" : 101 }
{ "_id" : 102 }
{ "_id" : 103 }
{ "_id" : 104 }
{ "_id" : 105 }

Projection Rules

Syntaxผลลัพธ์
{ "_id": 1 }Include เฉพาะ _id
{ "_id": 0 }Exclude _id (include ทุกอย่างอื่น)
{ "field1": 1, "field2": 1 }Include field1, field2 และ _id (default)
{ "field1": 1, "_id": 0 }Include field1, Exclude _id

ข้อจำกัด

  • ไม่สามารถ mix include/exclude ได้ (ยกเว้น _id)
  • คือ ไม่ได้ทำ { "a": 1, "b": 0 } พร้อมกัน
  • _id เป็นข้อยกเว้น: สามารถ exclude ได้แม้จะ include ฟิลด์อื่น

สรุป

  • find({}, { "_id": 1 }) = ดึงเฉพาะ _id
  • find({}, { "_id": 0 }) = ดึงทุกอย่างยกเว้น _id
  • Projection ลด network transfer และ memory usage
  • ใช้ในการ export ID, pagination, หรือการ join ฝั่ง application