12

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?

3 Answers 3

27

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");
Sign up to request clarification or add additional context in comments.

2 Comments

In Stackoverflow, I get points if you mark the answer as correct and/or vote it up. It also tells other people that this was the correct answer. Would you be able to do that?
why not @Gates ! sorry i must have done before but i am new to this site :)
5

You can try this according to the official documentation.

import org.bson.Document;
db.getCollection("restaurants").createIndex(new Document("cuisine", 1).append("address.zipcode", -1));

Official Mongo DB Driver Java documentation

Comments

4

A more modern and perhaps fluent approach using the factory methods could be:

import com.mongodb.client.model.Indexes;

collection
    .createIndex(
        Indexes.compoundIndex(
            Indexes.ascending("Age"),
            Indexes.descending("Name")
        )
    );

Found in the manual. Formatted for clarity; post-format to your own taste.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.