I've some collections on my database that have a 'Dynamic Name',
Let's say that I've some collections that store Animals data from an specific country,
So in my database Animals
I would have the following collections:
- Australia-Animals
- Japan-Animals
- Brazil-Animals
And from time to time I need to add new collections to my Database, currently I've an Script that add an Index to the country like:
public class CreateIndexForAnimalSpecies {
@ChangeSet(order = "1", id = "CreateIndexForAnimalSpecies", author = "Foo Bar")
public void createIndexForAnimalSpecies(final MongockTemplate template)
IndexOperations idx = mongockTemplate.indexOps("Australia-Animals");
Index index = new Index().named("specieIndex").on("specie", Direction.ASC).background();
idx.ensureIndex(index);
}
Basically this class does the job of creating the index for the Collection named Australia-Animals
but in the future if I add a new collection with a new Country Prefix I would have to copy this whole piece of code and change the Collection's name String.
I tried using *, $, %, as Regex but none of them worked. There's any alternative method along fetching the collections name and add to a list with contains("name")
?
I tough of something like:
Set<String> collections = mongockTemplate.getCollectionNames();
// Convert to a List<String>
for(String c: collections){
if(c.contains("-Animals"){
otherList.add(c);
}
}
otherList.forEach(item -> scriptToCreateIndex(item));
It works, but seems quite inefficient having to iterate over the collections to do the job.