How to create an index in MongoDB using Java?

JavaObject Oriented ProgrammingProgramming

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

Syntax

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

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 −

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

Output

Index created successfully
{"v": 2, "key": {"_id": 1}, "name": "_id_", "ns": "myDatabase.sampleCollection"}
{"v": 2, "key": {"age": 1}, "name": "age_1", "ns": "myDatabase.sampleCollection"}
raja
Published on 10-Apr-2020 07:30:25
Advertisements