Trong MongoDB, xóa index bằng dropIndex(). Trong Java, dùng phương thức dropIndex() của MongoCollection, truyền loại index và tên trường đã tạo.
Cú pháp (Shell)
db.COLLECTION_NAME.dropIndex({KEY:1})
Ví dụ 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[]) {
MongoClient mongo = new MongoClient("localhost", 27017);
MongoDatabase database = mongo.getDatabase("myDatabase");
database.createCollection("sampleCollection");
MongoCollection<Document> coll = database.getCollection("sampleCollection");
// Tạo 2 index
coll.createIndex(Indexes.ascending("age"));
coll.createIndex(Indexes.ascending("name"));
System.out.println("Danh sách index:");
for (Document index : coll.listIndexes()) {
System.out.println(index.toJson());
}
// Xóa index trên trường name
coll = database.getCollection("sampleCollection");
coll.dropIndex(Indexes.ascending("name"));
System.out.println("Danh sách index sau khi xóa:");
for (Document index : coll.listIndexes()) {
System.out.println(index.toJson());
}
}
}
Kết quả
Danh sách index:
{"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"}
Danh sách index sau khi xóa:
{"v": 2, "key": {"_id": 1}, "name": "_id_", "ns": "myDatabase.sampleCollection"}
{"v": 2, "key": {"age": 1}, "name": "age_1", "ns": "myDatabase.sampleCollection"}