Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

People also ask

Does MongoDB support compound indexes?

MongoDB supports compound indexes, where a single index structure holds references to multiple fields [1] within a collection's documents. The following diagram illustrates an example of a compound index on two fields: MongoDB imposes a limit of 32 fields for any compound index.

What is compound index in MongoDB?

Or in other words, compound indexes are those indexes where a single index field contains references to multiple fields. In MongoDB, the compound index can contain a single hashed index field, if a field contains more than one hashed index field then MongoDB will give an error.

How do you create an index in Java?

To create an index on a field or fields, pass an index specification document to the MongoCollection. createIndex() method. The MongoDB Java Driver provides the Indexes class that includes static factory methods to create index specification documents for the various MongoDB Index key types.


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?


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!