Вопрос

I have the following object structure:

@Document(collection = "user")
@TypeAlias("user")
public class User {
    @Id
    private ObjectId id;
    private Contact info = new Contact();
}

and here is the Contact pojo:

public class Contact {
    @Indexed(unique = true)
    private String mail;
}

But for some reasons not known to me, I don't see Spring-data creating a unique index for the property info.mail

To summarize, I have this json structure of user object: {_id:xxxxx,info:{mail:"abc@xyz.shoes"}}

And I want to create a unique index on info.mail using Spring data with the above pojo structure. Please help.

Это было полезно?

Решение

As far as I remember, annotating embedded fields with @Indexed will not work. @CompoundIndex is the way to go:

@Document(collection = "user")
@TypeAlias("user")
@CompoundIndexes({
    @CompoundIndex(name = "contact_email", def = "{ 'contact.mail': 1 }", unique = true)
})
public class User {
    @Id
    private ObjectId id;
    private Contact info = new Contact();
}

Другие советы

In my case I had a fresh spring boot application 2.3.0 with just @Document, @Id and @Indexed annotations. I was able to retrieve and insert documents but it refused to create the index other than the PK. Finally I figured that there is a property that you need to enable.

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

As a matter of fact it even works on nested objects without @Document annotation.

Hope this helps :)

Obsolete answer, this was with and older version of mongodb 1.x.


Had the same issue, it seems that your Contact class is missing the @Document annotation i.e.

@Document
public class Contact {
    @Indexed(unique = true)
    private String mail;
}

Should work, quote from the spring mongodb reference

Automatic index creation is only done for types annotated with @Document.

Extending @Xenobius's answer:

If any configuration extending AbstractMongoClientConfiguration is set, MongoMappingContext will back off. The result is:

spring.data.mongodb.auto-index-creation = true will not be effective

You will need add this into your own configuration:

    @Override
    protected boolean autoIndexCreation() {
        return true;
    }

ref: https://github.com/spring-projects/spring-boot/issues/28478#issuecomment-954627106

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top