4

I am trying to create unique compound index in mongodb using spring data.
But I see that the index is not created and the duplicate document is created in the DB.

My entity class:

@Document
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@CompoundIndexes(
        @CompoundIndex(name = "daybook_index", def = "{'date' : 1, 'vehicleNumber' : 1}", unique = true)
)
public class Daybook {

    private String date;
    private String vehicleNumber;
    private String unit;
}

I am using repository.insert() method to create the document.

When I see in mongo express I see only one index created on _id and the index defined in the entity class is not created.

enter image description here

Is it a bug in spring data or am I doing something wrong?

P.S.: I tried to delete the collection too before running the application but didn't help.

2 Answers 2

3

As @Saxon mentioned:

Spring Data MongoDB 3.0, automatic index creation is turned off by default.

Instead of adding code, I am able to create the index by adding the spring data configuration in application.properties

spring.data.mongodb.auto-index-creation=true
Sign up to request clarification or add additional context in comments.

Comments

1

As of Spring Data MongoDB 3.0, automatic index creation is turned off by default. To turn it on you might use the proper flag overriding the method from MongoConfigurationSupport:

public class MongoConfiguration extends AbstractMongoClientConfiguration {
    .....
    @Override
    protected boolean autoIndexCreation() {
        return true;
    }
}

otherwise you might create the index with appropriate instructions.

mongoOperations.indexOps(Daybook.class).ensureIndex(new Index().on("date", Direction.ASC).on("vehicleNumber", Direction.ASC).unique());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.