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

วิธีสร้าง Unique Field ใน MongoDB

เพื่อป้องกันข้อมูลซ้ำใน field เฉพาะ ให้สร้าง Unique Index โดยใช้ createIndex() พร้อม option {unique: true} MongoDB จะบังคับให้ค่าใน field นั้นไม่ซ้ำกันได้

สร้าง Unique Index และทดสอบ

> db.demo82.createIndex({"EmployeeName":1},{unique:true});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
> db.demo82.insertOne({"EmployeeName":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2bfb1b71bf0181ecc422a0") }
> db.demo82.insertOne({"EmployeeName":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2bfb1f71bf0181ecc422a1") }
> db.demo82.insertOne({"EmployeeName":"Chris"});
2020-01-25T13:54:00.410+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: test.demo82 index: EmployeeName_1 dup key: { : "Chris" }

แสดงข้อมูลที่บันทึกสำเร็จ

> db.demo82.find();

ผลลัพธ์ (เฉพาะ 2 รายการแรก เพราะรายการที่ 3 ถูกปฏิเสธ):

{ "_id" : ObjectId("5e2bfb1b71bf0181ecc422a0"), "EmployeeName" : "Chris" }
{ "_id" : ObjectId("5e2bfb1f71bf0181ecc422a1"), "EmployeeName" : "David" }

คำอธิบาย:

  • createIndex({"EmployeeName":1}, {unique:true}): สร้าง index แบบ ascending (1) บน field EmployeeName และบังคับ uniqueness
  • Error code 11000 (E11000) แสดงว่าเป็น duplicate key error
  • Unique index ทำงานอัตโนมัติ ทุกครั้งที่ insert หรือ update

กรณีพิเศษ: Sparse Unique Index

หากต้องการให้ unique เฉพาะเอกสารที่มี field นั้นอยู่จริง (ยอมให้ field หายไปได้) ให้เพิ่ม sparse: true:

db.demo82.createIndex({"EmployeeName":1}, {unique:true, sparse:true})

ข้อควรระวัง: Unique index ต้องสร้างก่อน insert ข้อมูลซ้ำ หากมีข้อมูลซ้ำอยู่แล้ว จะสร้างไม่ได้ ต้องลบข้อมูลซ้ำก่อน