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

Chuyển đổi chỉ mục duy nhất thành chỉ mục duy nhất thưa (sparse) trong MongoDB

Để tạo chỉ mục thưa (sparse index), hãy sử dụng tùy chọn sparse: true. Dưới đây là truy vấn để tạo chỉ mục:

> db.demo229.ensureIndex({"ClientName":1}, {unique: true});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }

Truy vấn sau đây hiển thị các chỉ mục hiện có:

> db.demo229.getIndexes();

Kết quả trả về:

[
  {
    "v" : 2,
    "key" : { "_id" : 1 },
    "name" : "_id_",
    "ns" : "test.demo229"
  },
  {
    "v" : 2,
    "unique" : true,
    "key" : { "ClientName" : 1 },
    "name" : "ClientName_1",
    "ns" : "test.demo229"
  }
]

Bây giờ hãy xóa chỉ mục hiện tại và tạo lại thành chỉ mục duy nhất thưa:

> db.demo229.dropIndex("ClientName_1");
{ "nIndexesWas" : 2, "ok" : 1 }
> db.demo229.ensureIndex({"ClientName":1}, {unique: true, sparse:true});
{ "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }

Kiểm tra lại các chỉ mục:

> db.demo229.getIndexes();

Kết quả hiện tại bao gồm thuộc tính sparse: true:

[
  {
    "v" : 2,
    "key" : { "_id" : 1 },
    "name" : "_id_",
    "ns" : "test.demo229"
  },
  {
    "v" : 2,
    "unique" : true,
    "key" : { "ClientName" : 1 },
    "name" : "ClientName_1",
    "ns" : "test.demo229",
    "sparse" : true
  }
]