Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Cách ngăn chặn dữ liệu trùng lặp trong MongoDB với Unique Index

Để đảm bảo một trường (hoặc tổ hợp các trường) không bị trùng lặp, hãy tạo Unique Index bằng phương thức createIndex() với tùy chọn unique: true.

Cú pháp

db.collection.createIndex({ "tênTrường": 1 }, { unique: true });

Ví dụ minh họa

Tạo unique index trên trường UserName:

> db.avoidDuplicateEntriesDemo.createIndex({ "UserName": 1 }, { unique: true });

Kết quả:

{
    "createdCollectionAutomatically" : true,
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 2,
    "ok" : 1
}

Chèn bản ghi đầu tiên:

> db.avoidDuplicateEntriesDemo.insertOne({ "UserName": "John" });

Kết quả: { "acknowledged" : true, "insertedId" : ObjectId("...") }

Thử chèn lại cùng giá trị "John":

> db.avoidDuplicateEntriesDemo.insertOne({ "UserName": "John" });

Lỗi trả về:

WriteError: E11000 duplicate key error collection: test.avoidDuplicateEntriesDemo index: UserName_1 dup key: { : "John" }

Chèn giá trị khác "Carol" thành công:

> db.avoidDuplicateEntriesDemo.insertOne({ "UserName": "Carol" });

Kiểm tra dữ liệu:

> db.avoidDuplicateEntriesDemo.find();

Kết quả:

{ "_id" : ObjectId("..."), "UserName" : "John" }
{ "_id" : ObjectId("..."), "UserName" : "Carol" }

Các trường hợp mở rộng

  • Unique Index tổ hợp (Compound Unique Index): db.users.createIndex({ "email": 1, "tenantId": 1 }, { unique: true }) - Cho phép email trùng nếu tenantId khác.
  • Partial Unique Index: Chỉ áp dụng unique khi field thỏa điều kiện (ví dụ: { partialFilterExpression: { status: "active" } }).
  • Sparse Unique Index: Bỏ qua document thiếu field đó ({ sparse: true, unique: true }).

Lưu ý: Unique index không thể tạo nếu dữ liệu hiện tại đã có giá trị trùng. Hãy dọn dẹp dữ liệu trước.