tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 No SQL > Mongo DB > How to drop index on Collection

How to drop index on Collection 

MongoDB is a scalable, high-performance, open source NoSQL database. It offers Ad hoc queries, Indexing, Replication, Load balancing, File storage (GridFS), Aggregation, MapReduce and Server-side JavaScript execution. This requires the library mongo-2.8.0.jar to be present in the classpath. The following example shows how to drop an Index on a Collection.

File Name  :  
com/bethecoder/tutorials/mongodb/tests/DropIndexTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.mongodb.tests;

import java.net.UnknownHostException;
import java.util.List;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class DropIndexTest {

  /**
   @param args
   */
  public static void main(String[] args) {

    try {
      //Connect to mongoDB with given IP and PORT
      Mongo mongo = new Mongo("localhost"27017);
      
      //Get the database object
      DB database = mongo.getDB("mytestdb");
      
      //Gets a collection with a given name.
      DBCollection collection = database.getCollection("students");
      
      //Show indexes
      showIndexes(collection);
      
      //Drops an index from this collection
      collection.dropIndex(new BasicDBObject("name"1));
      collection.dropIndex(new BasicDBObject("age", -1));
      
      System.out.println();
      System.out.println();
      
      //Show indexes
      showIndexes(collection);
          
    catch (UnknownHostException e) {
      e.printStackTrace();
    catch (MongoException e) {
      e.printStackTrace();
    }
  }
  
  private static void showIndexes(DBCollection collection) {
    //Get List of Indexes on a Collection
    List<DBObject> indexes = collection.getIndexInfo();

        for (DBObject o : indexes) {
            System.out.println(o);
        }
  }
}
   

It gives the following output,
{ "v" : 1 , "key" : { "_id" : 1} , "ns" : "mytestdb.students" , "name" : "_id_"}
{ "v" : 1 , "key" : { "name" : 1} , "ns" : "mytestdb.students" , "name" : "name_1"}
{ "v" : 1 , "key" : { "age" : -1} , "ns" : "mytestdb.students" , "name" : "age_-1"}


{ "v" : 1 , "key" : { "_id" : 1} , "ns" : "mytestdb.students" , "name" : "_id_"}



 
  


  
bl  br