How to create an index in MongoDB using Java?

In MongoDB to create an index, you need to use createIndex() method.



Where the key is the name of the file on which you want to create index and 1 is for ascending order. To create an index in descending order you need to use -1.

In Java, you can create an Index using the createIndex() method, to this method you need to pass the type of the index (ascending or descending) and the field name on which you want to create the index, as −



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 CreatingIndex {
   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
      //Retrieving the collection on which you want to create the index
      MongoCollection<Document> coll = database.getCollection("sampleCollection");
      //Creating an index
      System.out.println("Index created successfully");
      //Printing the list of indices in the collection
      for (Document index : coll.listIndexes()) {


Index created successfully
{"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

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started