10

I have the below class as my document.

@Data
@Builder
@Document(collection = "test")
public class TestData {
    @Id
    private String id;

    private String name;

    @Indexed(unique = true)
    private String hash;

}

Even if I'm using Indexed with unique enabled, I'm able to insert duplicate documents into collection. But if I generate index in mongo shell then it is working.

Is there any way where I can specify unique Index through code only?

9
  • What's the error/exception you are getting ? Please add some error/exception trace. Commented Jul 9, 2020 at 14:43
  • Shouldn't that be unique = true? Commented Jul 9, 2020 at 17:47
  • @Joe yes sorry, I'll update now, it's not working for both true and false. Commented Jul 10, 2020 at 4:38
  • @Amitkumar: There is no error, the entry just goes into mongo Commented Jul 10, 2020 at 4:39
  • 1
    See this duplicate question - The spring.data.mongodb.auto-index-creation=true property change worked for me stackoverflow.com/questions/53006818/… Commented Aug 13, 2020 at 22:27

3 Answers 3

4

Please use following code on application.properties file on spring boot application it will work.

spring.data.mongodb.auto-index-creation: true

Thank you

Sign up to request clarification or add additional context in comments.

Comments

3

This is how the compound index is used in my code

@Getter
@Setter
@Document
@CompoundIndexes({
@CompoundIndex(name = "name_author_idx", def = "{'name' : 1, 'author' : 1}", unique = true, background = true)})
public class Book implements Transformer {

    @Id
    private String id;

    @Field(name = "name")
    private String name;

    @Field(name = "author")
    private String author;

    @Field(name = "qty")
    private Integer qty;

    @Field(name = "price")
    private Double price;

    @Field(name = "created_time")
    private LocalDateTime createdTime = LocalDateTime.now();
}

Comments

1

If you're having a configuration component you should override the autoIndexCreation method like this:

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

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.