Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

เปลี่ยนดัชนีเฉพาะ (Unique Index) เป็นดัชนีเฉพาะแบบกระจาย (Sparse Unique Index) ใน MongoDB

สำหรับดัชนีแบบกระจาย (Sparse Index) ให้ใช้ตัวเลือก sparse:true ต่อไปนี้คือคำสั่งสำหรับสร้างดัชนี:

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

คำสั่งสำหรับแสดงดัชนีทั้งหมด:

> db.demo229.getIndexes();

ผลลัพธ์ที่ได้:

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

ตอนนี้ลองลบดัชนีเดิมและเปลี่ยนเป็นดัชนีเฉพาะแบบกระจาย (Sparse Unique Index) ใน 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 
}

คำสั่งแสดงดัชนีอีกครั้ง:

> db.demo229.getIndexes();

ผลลัพธ์ที่ได้ - สังเกตว่ามีฟิลด์ "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 
    } 
]