ใน MongoDB เพื่อลบดัชนี คุณต้องใช้เมธอด dropIndex()
ไวยากรณ์
db.COLLECTION_NAME.dropIndex({KEY:1})
ใน Java คุณสามารถลบดัชนีได้โดยใช้เมธอด dropIndex() โดยส่งประเภทของดัชนี (ascending หรือ descending) และชื่อฟิลด์ที่สร้างดัชนีไว้:
dropIndex(Indexes.ascending("name"));
ตัวอย่างโค้ด Java
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Indexes;
import org.bson.Document;
import com.mongodb.MongoClient;
public class DroppingIndex {
public static void main(String args[]) {
// สร้าง MongoDB client
MongoClient mongo = new MongoClient("localhost", 27017);
// เข้าถึงฐานข้อมูล
MongoDatabase database = mongo.getDatabase("myDatabase");
// สร้างคอลเลกชัน
database.createCollection("sampleCollection");
// ดึงคอลเลกชันที่ต้องการสร้างดัชนี
MongoCollection coll = database.getCollection("sampleCollection");
// สร้างดัชนี
coll.createIndex(Indexes.ascending("age"));
coll.createIndex(Indexes.ascending("name"));
System.out.println("List of collections: ");
for (Document index : coll.listIndexes()) {
System.out.println(index.toJson());
}
// ลบดัชนี
coll = database.getCollection("sampleCollection");
coll.dropIndex(Indexes.ascending("name"));
System.out.println("List of collections after deleting one ");
for (Document index : coll.listIndexes()) {
System.out.println(index.toJson());
}
}
}
ผลลัพธ์
List of collections:
{"v": 2, "key": {"_id": 1}, "name": "_id_", "ns": "myDatabase.sampleCollection"}
{"v": 2, "key": {"age": 1}, "name": "age_1", "ns": "myDatabase.sampleCollection"}
{"v": 2, "key": {"name": 1}, "name": "name_1", "ns": "myDatabase.sampleCollection"}
List of collections after deleting one
{"v": 2, "key": {"_id": 1}, "name": "_id_", "ns": "myDatabase.sampleCollection"}
{"v": 2, "key": {"age": 1}, "name": "age_1", "ns": "myDatabase.sampleCollection"}