How to drop an index in MongoDB using Java?


In MongoDB to drop an index, you need to use dropIndex() method.

Syntax

db.COLLECTION_NAME.dropIndex({KEY:1})

In Java, you can drop an Index using the dropIndex() method, to this method you need to pass the type of the index (ascending or descending) and the field name on which you have created it.

dropIndex(Indexes.ascending("name"));

Example

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());
      }
   }
}

Output

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"}

Updated on: 10-Apr-2020

397 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements