繁体   English   中英

如何在 Spring 数据 MongoDB 中动态创建集合?

[英]How to create a collection dynamically in Spring Data MongoDB?

如何在 spring 引导中创建基于月份的动态集合? 基于月份,我需要创建一个单独的集合,但具有相同的 model 属性。

您可以使用提供的月份名称和 JSON 架构验证来动态创建集合。 例如,使用MongoTemplate API 的 Spring 数据 MongoDB v2.2.7 以下代码在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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM