[英]How to create a collection dynamically in Spring Data MongoDB?
How to create a dynamic collection based on the month in the spring boot?如何在 spring 引导中创建基于月份的动态集合? Based on the month I need to create a separate collection but the same model attributes.
基于月份,我需要创建一个单独的集合,但具有相同的 model 属性。
You can create a collection dynamically by using a provided month name and JSON schema validation.您可以使用提供的月份名称和 JSON 架构验证来动态创建集合。 For example, using
MongoTemplate
API of Spring Data MongoDB v2.2.7 the following code creates a collection named myCollection_jun_2020
in the test
database.例如,使用
MongoTemplate
API 的 Spring 数据 MongoDB v2.2.7 以下代码在test
数据库中创建一个名为myCollection_jun_2020
的集合。
The MongoJsonSchema
applies the rules for creating the documents with specific attributes; MongoJsonSchema
应用规则来创建具有特定属性的文档; these are specified in the schema.这些在架构中指定。 If the rules are not followed the document insertion fails.
如果不遵守规则,则文档插入失败。 In the example, the following document can be inserted:
在示例中,可以插入以下文档:
{ "_id" : 1, "firstname" : "luke", "lastname" : "skywalker", "address" : { "postCode" : "99901" } }
And, the following cannot be:并且,以下不能是:
{ "_id" : 1, "firstname" : "leya", "lastname" : "skywalker", "address" : { "postCode" : "99901" } }
The Code:编码:
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.