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

วิธีป้องกันไม่ให้ MongoDB คืนค่า Object ID ระหว่างการค้นหาเอกสาร

เมื่อใช้เมธอด find() ใน MongoDB ระบบจะคืนค่าฟิลด์ _id (Object ID) มาเสมอ หากต้องการไม่ให้แสดง Object ID สามารถกำหนด _id: 0 ในพารามิเตอร์ projection ได้

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

> db.preventObjectIdDemo.insertOne({
    "StudentName": "Chris",
    "StudentDetails": [
      {
        "StudentTotalScore": 540,
        "StudentCountryName": "US"
      },
      {
        "StudentTotalScore": 489,
        "StudentCountryName": "UK"
      }
    ]
  });
{ "acknowledged": true, "insertedId": ObjectId("5ca20a9c66324ffac2a7dc63") }

แสดงข้อมูลทั้งหมด (มี _id)

> db.preventObjectIdDemo.find().pretty();

ผลลัพธ์

{
  "_id": ObjectId("5ca20a9c66324ffac2a7dc63"),
  "StudentName": "Chris",
  "StudentDetails": [
    { "StudentTotalScore": 540, "StudentCountryName": "US" },
    { "StudentTotalScore": 489, "StudentCountryName": "UK" }
  ]
}

ค้นหาโดยไม่แสดง _id

> db.preventObjectIdDemo.find(
  { _id: ObjectId("5ca20a9c66324ffac2a7dc63") },
  { StudentDetails: { $slice: [0, 1] }, '_id': 0 }
).pretty();

ผลลัพธ์ (ไม่มี _id)

{
  "StudentName": "Chris",
  "StudentDetails": [
    { "StudentTotalScore": 540, "StudentCountryName": "US" }
  ]
}

สรุป: เพิ่ม { '_id': 0 } ในอาร์กิวเมนต์ที่สองของ find() เพื่อซ่อน Object ID ออกจากผลลัพธ์