1

In my Spring MVC application I have the following Mongo entities:


@Document(collection = "users")
public class UserMongoEntity {

  @Id
  private String id;

  @NotBlank
  @Email
  @Indexed(unique = true, sparse = true)
  private String email;

  private String firstName;

and a Submission entity containing User as a field:


@Document(collection = "submissions")
public class SubmissionMongoEntity {

  @Id
  private String id;

  private Instant timestamp;

  @Valid
  private UserMongoEntity user;

When I make a request to insert a new User, I get an error if a user with the same email already exists, as expected. However, when I insert a submission with the same user twice, I get an exception for violating the uniqueness of the index: duplicate key error collection: user.email dup key.

I could remove the @Indexed, but I believe there is a better way.

Boyan Kushlev
  • 1,043
  • 1
  • 18
  • 35

1 Answers1

0

As far as i know there is no way to "disable" uniqueness for nested documents. as answered in this question mongo indexes main purpose is to speedup certain queries and less so about data validation.

if you do still want to keep the uniqueness one work around i could think off is exploiting mongo's unique compound index and missing values . create a unique compound index for email + a null field for user. while insert a submission set that user null field to be unique (either time hash or a unique submission id) thus creating a unique compound index that would not clash.

Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43