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

MongoDB ดึง _id ทั้งหมดของ Collection ด้วย Projection

การดึงเฉพาะ Field _id ของทุกเอกสารใน Collection สามารถทำได้โดยใช้ Projection Exclusion Mode (0) กับ Field อื่นๆ เนื้อหานี้สาธิตการใช้ Variable Iterator เพื่อเก็บ Cursor แล้ว Iterate

ตัวอย่างข้อมูลทดสอบ

> db.demo169.insertOne({"StudentName":"Chris"});
{ "acknowledged": true, "insertedId": ObjectId("5e36975e9e4f06af551997d7") }

> db.demo169.insertOne({"StudentName":"Bob"});
{ "acknowledged": true, "insertedId": ObjectId("5e3697629e4f06af551997d8") }

> db.demo169.insertOne({"StudentName":"David"});
{ "acknowledged": true, "insertedId": ObjectId("5e3697679e4f06af551997d9") }

แสดงข้อมูลทั้งหมด

> db.demo169.find();
{
  "_id": ObjectId("5e36975e9e4f06af551997d7"),
  "StudentName": "Chris"
}
{
  "_id": ObjectId("5e3697629e4f06af551997d8"),
  "StudentName": "Bob"
}
{
  "_id": ObjectId("5e3697679e4f06af551997d9"),
  "StudentName": "David"
}

Query ดึงเฉพาะ _id (Exclusion Mode)

> var iterator = db.demo169.find({}, {"StudentName": 0});

Iterate ผลลัพธ์

> iterator;
{
  "_id": ObjectId("5e36975e9e4f06af551997d7")
}
{
  "_id": ObjectId("5e3697629e4f06af551997d8")
}
{
  "_id": ObjectId("5e3697679e4f06af551997d9")
}

คำอธิบายและวิธีทางเลือก

  • Projection {"StudentName": 0} = Exclude StudentName, Include _id (Default)
  • Variable iterator เก็บ Cursor Object, พิมพ์ชื่อ Variable ใน Shell จะ Auto-Iterate แสดงทุก Document
  • วิธีง่ายกว่า (Inclusion Mode):
    db.demo169.find({}, { _id: 1, StudentName: 0 })
    หรือแค่ db.demo169.find({}, { _id: 1 }) (Inclusion Mode Auto-Exclude อื่นๆ)
  • Aggregation $project (สำหรับ Pipeline):
    db.demo169.aggregate([{ $project: { _id: 1 } }])
  • Distinct _id (หากต้องการ Array):
    db.demo169.distinct("_id")
  • Performance: Projection เล็ก (แค่ _id) ช่วยลด Network Transfer และ Memory Usage