在MongoDB中删除索引,您需要使用dropIndex()方法。
db.COLLECTION_NAME.dropIndex({KEY:1})
在Java中,可以使用dropIndex()方法删除索引,您需要将索引的类型(升序或降序)和在其上创建字段的名称传递给该方法。
dropIndex(Indexes.ascending("name"));
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客户端 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 colections: "); for (Document index : coll.listIndexes()) { System.out.println(index.toJson()); } //删除索引 coll = database.getCollection("sampleCollection"); coll.dropIndex(Indexes.ascending("name")); System.out.println("List of colections after deleting one "); for (Document index : coll.listIndexes()) { System.out.println(index.toJson()); } } }
输出结果
List of colections: {"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 colections after deleting one {"v": 2, "key": {"_id": 1}, "name": "_id_", "ns": "myDatabase.sampleCollection"} {"v": 2, "key": {"age": 1}, "name": "age_1", "ns": "myDatabase.sampleCollection"}