Lafox.Net Lafox.Net World
How to create indexes in MongoDB from Java

How to create indexes in MongoDB from Java

You can create indexes in MongoDB from Spring boot application using the following code:
import javax.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.stereotype.Repository;

@Repository
@RequiredArgsConstructor
public class TestRepository {
    public static final String COLLECTION_NAME = "testCollection";

    private final MongoTemplate mongoTemplate;
    @PostConstruct
    private void initIndexes() {
            mongoTemplate.indexOps(COLLECTION_NAME).ensureIndex(new Index("fieldName", Direction.ASC).background());
    }

}
In this code MongoTemplate bean injected by spring as dependency. You also can use

MongoOperations

interface.
private final MongoTemplate mongoTemplate;
Function initIndexes() annotated as @PostConstruct will be run by Spring once on beanCreation. 1(source) 2(source)