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.