0

For Single Field indexes in mongodb we can set the IndexOptions as below

collection.createIndex(
            Indexes.ascending(actualIndexFieldName), new IndexOptions().background(true));

But not sure how to set the IndexOptions for a compound index in java.

Thanks in Advance

Abhi
  • 69
  • 6

1 Answers1

1

Yes, You can.

Refer

java.lang.String createIndex(Bson keys,
                             IndexOptions indexOptions)
Create an index with the given keys and options.
Parameters:
keys - an object describing the index key(s), which may not be null.
indexOptions - the options for the index

To Use Indexes

public static Bson compoundIndex(java.util.List<? extends Bson> indexes)

Refer

ArrayList<Document> indexes = new ArrayList<Document>();
indexes.add(Indexes.descending("stars")); 
indexes.add(Indexes.ascending("name"));
collection.createIndex(indexes, indexOptions);
Gibbs
  • 21,904
  • 13
  • 74
  • 138
  • Thanks .. but how can i create the compound index with index options , if am creating this way. collection.createIndex(Indexes.compoundIndex(Indexes.descending("stars"), Indexes.ascending("name"))); – Abhi Aug 08 '20 at 05:34
  • i think there is a small correction.. the syntax will be like this collection.createIndex(Indexes.compoundIndex(indexes), new IndexOptions().background(true)); and the list is not Document , it must be a Bson list List indexes = new ArrayList(); – Abhi Aug 08 '20 at 06:06
  • I will check that Abhi. I see list element extends Bson. Document extends Bson. So should work. I ll check and correct it. Thanks for letting us know – Gibbs Aug 08 '20 at 06:26