Đối với chỉ mục thưa thớt, hãy sử dụng thưa thớt:true . Sau đâ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
} Sau đây là truy vấn để hiển thị các chỉ mục -
> db.demo229.getIndexes();
Điều này sẽ tạo ra kết quả sau -
[
{
"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ờ chúng ta hãy giảm một chỉ mục và thay đổi một chỉ mục duy nhất thành một chỉ mục duy nhất thưa thớt trong MongoDB -
> 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
} Sau đây là truy vấn để hiển thị các chỉ mục -
> db.demo229.getIndexes();
Điều này sẽ tạo ra kết quả sau -
[
{
"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
}
]