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

时间:2020-05-20 09:36:05

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

如何基于春季启动中的月份创建动态集合? 基于月份,我需要创建一个单独的集合,但具有相同的模型属性。

1 个答案:

答案 0 :(得分:1)

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

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;
}
相关问题