0

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.

Johnnes Souza
  • 361
  • 1
  • 8
  • 22
  • It may not be an efficient design to have a collection for each animal - a single animal collection with animal type field would be easy to code, index, query and maintain. Of course, very large sets can be managed the way you are storing but coding and maintenance is in-efficient. Generally, very large datasets are distributed in a sharded cluster. – prasad_ Jul 13 '21 at 05:40
  • Yeah, I totally agree with you, I just used animals as an example, this is not the real case. – Johnnes Souza Jul 13 '21 at 11:42

0 Answers0