2

I have a problem like this. The "name" and "lastname" fields are not unique individually. But name + lastname I want to be unique. So the same "name" can be more than one, or the same "lastname" can be more than one, but I want to have just one "name + lastname".

For example:

Registered in the database:

Name: "Erdem" lastName: "ÖZDEMİR"

Name: "Erdem" lastName: "AYDEMİR"

When I want to record the above record, I want it to

record successfully

Name: "Ahmet" lastName: "ÖZDEMİR"

When I want to record the above record, I want it to

record successfully

Name: "Erdem" lastName: "ÖZDEMİR"

But since it's the same name and lastname here,

give me an error!

How can it be done? How can a solution be created in the entity? My problem is a little ridiculous, but I need to take care of it.

Contact.java

@Document(collection = "contact")
public class Contact implements Serializable {

    @Id
    private String id;
    private String name;
    private String lastName;
    private List<String> phones;

//get & set
}

1 Answer 1

3

If you create a unique index on name, lastName then MongoDB will reject any writes which breach that uniqueness.

For example:

db.collection.createIndex( { "name": 1, "lastName": 1 }, { unique: true } )

MongoDB will return a WriteError like this if your unique index is breached:

"writeError" : {
      "code" : 11000,
      "errmsg" : "E11000 duplicate key error index: test.collection.$a.b_1 dup key: { : null }"
   }
Sign up to request clarification or add additional context in comments.

1 Comment

@CompoundIndex(name = "name_lastName_idx", def = "{'name' : 1, 'lastName' : 1}", unique = true) ty for helping. i use this annatation create index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.