1
votes

I am trying to create unique index for my collection in java class using @Indexed annotation in spring-boot. When I use @Indexed on a field in pojo of collection's document:

   @Indexed(unique = true)
    private String name;

Where name field contains string consisting of English alphabet and I want to stop duplicate entry of name field. Field name is not working as unique and I am able to add documents having duplicate name field. To make it work I have to make id field unique=false:

@Indexed(unique = false)
    String id;

Is this correct approach, can we make id field unique=false and make some other field unique=true to make that field unique.

1
Not sure what exactly you are asking. you can specify just @Indexed without specifying unique true or false. - pvpkiran

1 Answers

0
votes

I am not sure how @Indexed(unique = false) is letting you define the unique indexes.

But the fact is that if there is already existing index with name you are trying to insert another document then it will not let you insert. Because indexes are unique.

You can check if the has created or not is mongoDB like below :

db.collection_name.getIndexes();

If there exist an index with then you cannot create another index with the same name.