การสร้างดัชนีที่บังคับให้ค่าไม่ซ้ำ (Unique Index) ใช้ createIndex() พร้อมตัวเลือก unique: true
> db.demo658.createIndex({FirstName: 1}, {unique: true, sparse: true});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
ทดสอบ insert:
> db.demo658.insertOne({"FirstName": "John", "LastName": "Smith"});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea067144deddd72997713d9") }
> db.demo658.insertOne({"FirstName": "Adam", "LastName": "Smith"});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea0671c4deddd72997713da") }
> db.demo658.insertOne({"FirstName": "John", "LastName": "Doe"});
2020-04-22T21:17:46.072+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: onlinecustomertracker.demo658 index: FirstName_1 dup key: { : "John" }
: WriteError({ "index" : 0, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: onlinecustomertracker.demo658 index: FirstName_1 dup key: { : \"John\" }", "op" : { "_id" : ObjectId("5ea067224deddd72997713db"), "FirstName" : "John", "LastName" : "Doe" } })
แสดงข้อมูล (John Doe ไม่ได้ถูก insert):
> db.demo658.find();
ตัวเลือกสำคัญ
| Option | คำอธิบาย |
|---|---|
unique: true | บังคับค่าไม่ซ้ำ (throw error ถ้าซ้ำ) |
sparse: true | ไม่อินเด็กเอกสารที่ไม่มีฟิลด์นี้ (อนุญาต null หลายค่า) |
partialFilterExpression | สร้าง index เฉพาะเอกสารที่ match filter (MongoDB 3.2+) |