I have a mongodb collection that needs to be cleaned before a certain process starts, i do this by using mongoTemplate.dropCollection() method becouse it is much faster than using the deleteAll() method on the repository.
The problem arises when i introduced indexes, my model is annotated as follows:
@Document
public class TestModel {
@Indexed
private String testField;
}
and repository
public interface TestModelRepository extends MongoRepository<TestModel, String> {
}
This makes sure that the index is created at application start time
i noticed that by using the repository's deleteAll() method instead of dropping the collection preserves the index, but i was wondering if there is a way with spring-data to make sure that indexes are in place when i make an insert.
also any method to re-create indexes based on the annotated model after drop would be appreciated.
something like
mongoTemplate.createIndexes( TestModel.class );
How can i achieve this?
There is no method like this
mongoTemplate.createIndexes( TestModel.class );
Before deleting, just get the indexInfo and after dropping collection, Recreate the indexes.
List<IndexInfo> indexInfo = mongoTemplate.indexOps(TestModel.class).getIndexInfo();
mongoTemplate.dropCollection(TestModel.class);
indexInfo.forEach(index -> {
DBObject indexOptions = new BasicDBObject();
if(! index.getName().equals("_id_"))
{
indexOptions.put(index.getName(), 1);
CompoundIndexDefinition indexDefinition = new CompoundIndexDefinition(indexOptions);
indexDefinition.named(index.getName());
mongoTemplate.indexOps(TestModel.class).ensureIndex(indexDefinition);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With