Spring boot mongo db index (unique=true) not working
Asked Answered
M

3

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?

Messenia answered 9/7, 2020 at 13:44 Comment(9)
What's the error/exception you are getting ? Please add some error/exception trace.Microstructure
Shouldn't that be unique = true?Dentate
@Dentate yes sorry, I'll update now, it's not working for both true and false.Messenia
@Amitkumar: There is no error, the entry just goes into mongoMessenia
@Indexed can't be applied at class level, It should be applied at field level. Use @CompoundIndex instead.Microstructure
@Amitkumar: Tried that too @CompoundIndex(def = "{ 'hash': 1 }", unique = true) , it's not workingMessenia
@Amitkumar: This is a syntax error, can't be done like that.Messenia
See this duplicate question - The spring.data.mongodb.auto-index-creation=true property change worked for me #53007318Cosby
Does this answer your question? Spring boot / mongo wont create index with the index annotationCosby
M
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();
}
Miscue answered 17/2, 2022 at 7:26 Comment(0)
N
3

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

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

Thank you

Neale answered 9/12, 2022 at 16:54 Comment(0)
P
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;
}}
Parent answered 27/12, 2022 at 0:22 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.