How to create a compound index in MongoDB through Java driver?

jad001 picture jad001 · Jul 15, 2012 · Viewed 9.5k times · Source

I want to create compound index on Age and Name in MongoDB through Java driver and here is my syntax:

coll.ensureIndex(new BasicDBObject("Age", 1),new BasicDBObject("Name", -1));
List <DBObject> list = coll.getIndexInfo();

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

but it create only 1 index not compund index and give me result this:

{ "v" : 1 , "key" : { "_id" : 1} ,"ns" :"EmployeeData.EmpPersonalData", "name":"_id_"}
{ "v" : 1 , "key" : { "Age" : 1} , "ns" : "EmployeeData.EmpPersonalData" , "name" : "Age_1" , "Name" : -1}

So how can compund index on collection can be created through java driver?

Answer

Gates VP picture Gates VP · Jul 15, 2012

If you look at your code, you have actually called ensureIndex with two parameters. Your first parameter was the key and your second parameter became some extra field: Name: -1.

What you are looking to pass in the first parameter is this object {"Age":1, "Name":-1}. What you actually passed was {"Age":1}, {"Name":-1}.

So you want to do something like this:

BasicDBObject obj = new BasicDBObject();
obj.put("Age", 1);
obj.put("Name", -1);
coll.ensureIndex(obj);

Note that the index will be created with a default name. To provide a specific name do the following:

coll.ensureIndex(obj, "MyName");