Search code examples
springmongodbspring-bootconstraintsspring-data-mongodb

How to add mongodb constraint in springboot to validate multiple concurrent request object having same username and active flag


I have pojo class

@Data
@Document(collection="user")
public class User{
@Id
private long id;
private String username;
private String sessionId;
private boolean active;
}

And my Repository

public interface UserRepository extends MongoRepository<User, String> {

}

In my service class i'm doing

repository.save(user);

When Parallel requests are made in database there are multiple records created for the same username and the active status is true. only one true active status record should be created per username and can have multiple false active records. How to add mongodb database level constraint to check this. Any suggestions


Solution

  • You could use compaund, partial, unique index

    @CompoundIndex(
        name = "unique_active_username", 
        def = "{'username' : 1}", 
        partialFilter = "{active: { $eq: true }}", 
        unique = true)
    @Data
    @Document(collection="user")
    public class User{
        @Id
        private long id;
        private String username;
        private String sessionId;
        private boolean active;
    }