javaspringmongodbspring-bootspring-mongodb

How do I allow duplicate key for MongoDB in Spring Boot Project?


This is how my document looks like

@Getter
@Document(collection = "team")
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Team extends BaseTimeEntity {
    ....
    private List<User> designers = new ArrayList<>();
    ....
}

The BaseTimeEntity, which is extending from this class, looks like this.

@Getter
public abstract class BaseTimeEntity {

    @MongoId
    private ObjectId id;

    @CreatedDate
    @Field(name = "created_date")
    private LocalDateTime createdDate;

    @LastModifiedDate
    @Field(name = "modified_date")
    private LocalDateTime modifiedDate;

    @Field(name = "is_deleted")
    protected Boolean isDeleted;

    @Field(name = "schema_version")
    protected String schemaVersion = "1.0";
}

After adding a single Team data into the database. When I try to create a new data with this class, leaving the designers list blank again, I get org.springframework.dao.DuplicateKeyException.

This is the error msg that I get.

org.springframework.dao.DuplicateKeyException: Write operation error on server 
localhost:27017. Write error: WriteError{code=11000, message='E11000 duplicate key error 
collection: gabojait.team index: designer.username dup key: { designer.username: null }', 
details={}}.; nested exception is com.mongodb.MongoWriteException: Write operation error 
on server localhost:27017. Write error: WriteError{code=11000, message='E11000 duplicate 
key error collection: gabojait.team index: designer.username dup key: { 
designer.username: null }', details={}}.

How do I fix this problem?


Solution

  • your collection has an index defined on the designer.username field. remove it or provide a unique value to the username, or allow non-unique option on the index.