Search code examples
javaspringmongodbspring-data-mongodb

@Indexed on nested property not working in Spring-data for mongo


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:"[email protected]"}}

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


Solution

  • 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();
    }