如何使用 Java 删除 MongoDB 中的索引?

javaobject oriented programmingprogramming更新于 2025/10/7 21:32:17

在 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("集合列表:");
      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"}

相关文章


有用资源