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


要在 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[] ) {
      //Creating a MongoDB client
      MongoClient mongo = new MongoClient( "localhost" , 27017 );
      //Accessing the database
      MongoDatabase database = mongo.getDatabase("myDatabase");
      //Creating a collection
      database.createCollection("sampleCollection");
      //Retrieving the collection on which you want to create the index
      MongoCollection coll = database.getCollection("sampleCollection");
      //Creating indexes
      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());
      }
      //Dropping the index
      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"}

更新时间:10-Apr-2020

520 次观看

开启您的职业生涯

完成课程以获得认证

开始学习
广告