MongoException$DuplicateKey: E11000 duplicate key error index - @Version

Obviously, we get this exception when we try to update/insert a document(record) with duplicate key field in MongoDB collection(table). There exists several explanation on this:

But, I was getting this error in a different scenario:

1) I already had a model User and data in it. Sample data were being created using mongeez change log file
2) Later, I added a new auditing field @Version to the entity definition.
3) When updating a User record, I got the above exception ( MongoException$DuplicateKey: E11000 duplicate key error index )

User entity :

@Document(collection = "user")
public class User implements Serializable {

    @NotNull    @Size(min = 5, max = 100)
    @Id    private String id;

    @Version    Long version; // THIS WAS ADDED LATER
    @Size(max = 50)
    private String firstName;
    private String lastName;

    private String email;


Solution :

I added a property version and initialized to 1 in all documents

Mongo Change Log  : Using mongeez

    <changeSet changeId="ChangeSet-2" author="gtiwari">
                "_id" : "user1",
                "first_name": "",
                "last_name": "User 1",
                "email": "user1@localhost",
                "version":1  --> I UPDATED ALL user RECORDS'S VERSION = 1 TO SOLVE THIS

No comments :

Post a Comment

Your Comment and Question will help to make this blog better...