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)
@Field("first_name")
private String firstName;
@Field("last_name")
private String lastName;
@Email
private String email;
Solution :
I added a property version and initialized to 1 in all documents
Mongo Change Log : Using mongeez
<mongoChangeLog>
<changeSet changeId="ChangeSet-2" author="gtiwari">
<script>
db.user.insert(
{
"_id" : "user1",
"first_name": "",
"last_name": "User 1",
"email": "user1@localhost",
"version":1 --> I UPDATED ALL user RECORDS'S VERSION = 1 TO SOLVE THIS
});