首页 > 解决方案 > MongoDb:如何为 Java 中的复合索引设置 IndexOptions 背景为真

问题描述

对于 mongodb 中的单字段索引,我们可以设置 IndexOptions 如下

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

但不确定如何在 java 中为复合索引设置 IndexOptions。

提前致谢

标签: mongodbindexingmongodb-javamongodb-indexes

解决方案


是的你可以。

参考

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

使用Indexes

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

参考

ArrayList<Document> indexes = new ArrayList<Document>();
indexes.add(Indexes.descending("stars")); 
indexes.add(Indexes.ascending("name"));
collection.createIndex(indexes, indexOptions);

推荐阅读