Fazlan Ahamed
Fazlan Ahamed

Reputation: 241

How to create a collection dynamically in Spring Data MongoDB?

How to create a dynamic collection based on the month in the spring boot? Based on the month I need to create a separate collection but the same model attributes.

Upvotes: 1

Views: 3460

Answers (1)

prasad_
prasad_

Reputation: 14287

You can create a collection dynamically by using a provided month name and JSON schema validation. 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.

The MongoJsonSchema applies the rules for creating the documents with specific attributes; 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;
}

Upvotes: 2

Related Questions