สร้าง Unique Index เพื่อห้ามข้อมูลซ้ำ
ใช้เมธอด createIndex() พร้อมตัวเลือก unique: true เพื่อบังคับให้ฟิลด์นั้นไม่มีค่าซ้ำกัน
ไวยากรณ์
db.yourCollectionName.createIndex({"yourFieldName": 1}, {unique: true});
ตัวอย่าง
สร้างดัชนี unique บนฟิลด์ UserName:
> db.avoidDuplicateEntriesDemo.createIndex({"UserName": 1}, {unique: true});
ผลลัพธ์:
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
ทดสอบการแทรกข้อมูลซ้ำ
> db.avoidDuplicateEntriesDemo.insertOne({"UserName":"John"}); // สำเร็จ
> db.avoidDuplicateEntriesDemo.insertOne({"UserName":"John"}); // Error
ข้อผิดพลาด:
E11000 duplicate key error collection: test.avoidDuplicateEntriesDemo index: UserName_1 dup key: { : "John" }
แทรกข้อมูลใหม่ที่ไม่ซ้ำ:
> db.avoidDuplicateEntriesDemo.insertOne({"UserName":"Carol"});
แสดงข้อมูลทั้งหมด:
> db.avoidDuplicateEntriesDemo.find();
ผลลัพธ์:
{ "_id" : ObjectId("..."), "UserName" : "John" }
{ "_id" : ObjectId("..."), "UserName" : "Carol" }