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

วิธีลบดัชนีทั้งหมดจากทุกคอลเลกชันใน MongoDB Database

ใช้ getCollectionNames() วนลูปพร้อม runCommand({ dropIndexes: ..., index: "*" }) เพื่อลบดัชนีทั้งหมด (ยกเว้น _id)

รูปแบบคำสั่ง

db.getCollectionNames().forEach(function(collectionName) {
    db.runCommand({ dropIndexes: collectionName, index: "*" });
});

ตัวอย่างเต็มรูปแบบ

1. ตรวจสอบ database ปัจจุบัน

> db
Test

2. ดู Index ก่อนลบ (ตัวอย่างคอลเลกชัน indexingDemo)

> db.indexingDemo.getIndexes();
[
    { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.indexingDemo" },
    { "v" : 2, "key" : { "StudentFavouriteSubject" : 1 }, "name" : "StudentFavouriteSubject_1", "ns" : "test.indexingDemo", "background" : true }
]

3. ลบ Index ทั้งหมดจากทุกคอลเลกชัน

> db.getCollectionNames().forEach(function(allCollectionName) {
    db.runCommand({ dropIndexes: allCollectionName, index: "*" });
});

4. ตรวจสอบหลังลบ

> db.indexingDemo.getIndexes();
[
    { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.indexingDemo" }
]

เหลือแค่ _id_ index (ไม่สามารถลบได้)

คำอธิบาย

  • index: "*" = ลบทุก index ยกเว้น _id
  • dropIndexes command ต้องรันใน context ของ database นั้นๆ
  • getCollectionNames() คืน array ของชื่อคอลเลกชัน

กรณีใช้งาน

  • Reset database ก่อนสร้าง index ใหม่
  • Performance testing
  • Migration script

ข้อควรระวัง

  • การลบ index อาจทำให้ query ช้าลงชั่วคราว
  • ควร backup หรือทดสอบใน staging ก่อน
  • _id index ไม่สามารถลบได้ (System index)

สรุป

ใช้ forEach วนลูปคอลเลกชันทั้งหมด เรียก dropIndexes command ด้วย index: "*" เพื่อลบ index ทุกตัวยกเว้น _id ใช้ได้ใน MongoDB shell โดยตรง