1

In the project we need to change collection name suffix everyday based on date.

So one day collection is named:

samples_22032019

and in the next day it is

samples_23032019

Everyday I need to change suffix and recompile spring-boot application because of this. Is there any way I can change this so the collection/table can be calculated dynamically based on current date? Any advice for MongoRepository?

Marcin Kapusta
  • 5,076
  • 3
  • 38
  • 55

2 Answers2

1

Considering the below is your bean. you can use @Document annotation with spring expression language to resolve suffix at runtime. Like show below,

@Document(collection = "samples_#{T(com.yourpackage.Utility).getDateSuffix()}")
public class Samples {
   private String id;
   private String name;
}

Now have your date change function in a Utility method which spring can resolve at runtime. SpEL is handy in such scenarios.

package com.yourpackage;

public class Utility {
  public static final String getDateSuffix() {
     //Add your real logic here, below is for representational purpose only.
     return DateTime.now().toDate().toString();;
  }
}

HTH!

-1

Make a cron job to run daily and generateNewName for your collection and execute the below code. Here I am getting collection using MongoDatabse than by using MongoNamespace we can rename the collection. To get old/new collection name you can write a separate method.

@Component
public class RenameCollectionTask {

  @Scheduled(cron = "${cron}")
  public void renameCollection() {

    // creating mongo client object
    final MongoClient client = new MongoClient(HOST_NAME, PORT);
    // selecting the mongo database
    final MongoDatabase database = client.getDatabase("databaseName");
    // selecting the mongo collection
    final MongoCollection<Document> collection = database.getCollection("oldCollectionName");
    // creating namespace
    final MongoNamespace newName = new MongoNamespace("databaseName", "newCollectionName");
    // renaming the collection
    collection.renameCollection(newName);
    System.out.println("Collection has been renamed");
    // closing the client
    client.close();
  }
}

To assign the name of the collection you can refer this so that every time restart will not be required.

The renameCollection() method has the following limitations:
1) It cannot move a collection between databases.
2) It is not supported on sharded collections.
3) You cannot rename the views.
Refer this for detail.

Nishant Bhardwaz
  • 924
  • 8
  • 21