【问题标题】:MongoDb : How to set IndexOptions background true for compound indexes in JavaMongoDb:如何在 Java 中为复合索引设置 IndexOptions 背景为真
【发布时间】:2020-08-08 05:09:26
【问题描述】:

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

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

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

提前致谢

【问题讨论】:

    标签: mongodb indexing mongodb-java mongodb-indexes


    【解决方案1】:

    是的,你可以。

    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
    

    使用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);
    

    【讨论】:

    • 谢谢.. 但是如果我以这种方式创建,我如何使用索引选项创建复合索引。 collection.createIndex(Indexes.compoundIndex(Indexes.descending("stars"), Indexes.ascending("name")));
    • 我认为有一个小的更正.. 语法将像这样 collection.createIndex(Indexes.compoundIndex(indexes), new IndexOptions().background(true));并且列表不是 Document ,它必须是 Bson 列表 List indices = new ArrayList();
    • 我会检查那个 Abhi。我看到列表元素扩展了 Bson。文档扩展了 Bson。所以应该工作。我会检查并纠正它。感谢您告知我们
    猜你喜欢
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 2022-01-22
    • 2012-03-05
    • 2022-10-24
    • 1970-01-01
    相关资源
    最近更新 更多