【问题标题】:How to create a collection dynamically in Spring Data MongoDB?如何在 Spring Data MongoDB 中动态创建集合?
【发布时间】:2020-05-20 09:36:05
【问题描述】:

spring boot中如何创建基于月份的动态集合? 根据月份,我需要创建一个单独的集合,但模型属性相同。

【问题讨论】:

    标签: java mongodb spring-boot spring-data-mongodb


    【解决方案1】:

    您可以使用提供的月份名称和 JSON 架构验证来动态创建集合。例如,使用 Spring Data MongoDB v2.2.7 的MongoTemplate API,以下代码在test 数据库中创建一个名为myCollection_jun_2020 的集合。

    MongoJsonSchema 应用创建具有特定属性的文档的规则;这些在架构中指定。如果不遵守规则,则文档插入失败。在示例中,可以插入以下文档:

    { "_id" : 1, "firstname" : "luke", "lastname" : "skywalker", "address" : { "postCode" : "99901" } }
    

    而且,以下不能是:

    { "_id" : 1, "firstname" : "leya", "lastname" : "skywalker", "address" : { "postCode" : "99901" } }
    

    守则:

    MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "test");
    String month = "jun_2020";
    String collectionName = "myCollection_" + month;
    MongoCollection<Document> coll = mongoOps.createCollection(collectionName, getSchemaOption());
    System.out.println(coll.getNamespace());    // prints test.myCollection_jun_2020
    
    // Method returns the collection option object with schema validation.
    private static CollectionOptions getSchemaOption() {
        MongoJsonSchema schema = MongoJsonSchema.builder()
                                                   .required("firstname", "lastname")
                                                   .properties(
                                                       string("firstname")
                                                           .possibleValues("luke", "han"),
                                                       object("address")
                                                           .properties(string("postCode")
                                                               .minLength(4).maxLength(5))
                                                   ).build();
        CollectionOptions options = CollectionOptions.empty().schema(schema);
        return options;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 2011-10-10
      • 2015-12-17
      相关资源
      最近更新 更多