在春季引导中如何根据月份创建动态集合? 根据月份我需要创建一个单独的集合,但模型属性相同。
您可以通过使用提供的月份名称和JSON模式验证来动态创建一个集合。例如,使用 MongoTemplate
以下代码创建了一个名为 "Spring Data MongoDB v2.2.7 "的集合。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;
}