Sample Java Program to Create Index in MongoDB 3 Java Driver . This snipped also contains older code which was used to create index . You just need to create a BasicDBObject with key as a name on which you want to create a index , and value will be 1 or -1 . if you create it with 1 then it will create a ascending index , and if you create with -1 , then it will create descending index .
package mongoDBExample; import java.util.Arrays; import java.util.List; import org.bson.Document; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.ListIndexesIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; public class MongoDBTest { public static void main(String[] args) { MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017")); /*MongoDatabase database = mongoClient.getDatabase("Test"); ListPost Comments And Suggestions !!books = Arrays.asList(1251,2512); Document person = new Document("_id", "ABHSIHEK") .append("name", "java roots") .append("address", new BasicDBObject("street", "sad java") .append("city", "mongos") .append("state", "mongod") .append("zip", 5151)) .append("books", books); MongoCollection collection= database.getCollection("people"); collection.insertOne(person);*/ MongoDatabase database = mongoClient.getDatabase("Test"); MongoCollection collection= database.getCollection("people"); //create index on name field //use 1 for ascending index , -1 for descending index BasicDBObject index = new BasicDBObject("name",1); collection.createIndex(index); System.out.println(" index created successfully "); ListIndexesIterable indexes = collection.listIndexes(BasicDBObject.class); MongoCursor cursor = indexes.iterator(); while(cursor.hasNext()) { BasicDBObject getCreatedIdx = cursor.next(); System.out.println("index is : "+ getCreatedIdx.toString()); } mongoClient.close(); /** * Older code which is deprecated in 3.0 */ /* DB db = mongoClient.getDB("Test"); List books = Arrays.asList(27464, 747854); DBObject obj = new BasicDBObject("_id", "javaroots").append("name", "java roots") .append("address", new BasicDBObject("street", "awesome java") .append("city", "mongos") .append("state", "mongod") .append("zip", 5151)) .append("books", books);; DBCollection col = db.getCollection("people"); col.insert(obj); col.createIndex("name");*/ } }