Tuesday, March 25, 2014

MongoDB error E11000 duplicate key error index on Spring

When trying to insert the document with the same id on MongoDB, MongoDB will return an error of E11000 duplicate key error index.
> db.users.insert({"_id":"jsmith", "firstname": "John", "lastname": "Smith"})
> db.users.insert({"_id":"jsmith", "firstname": "John", "lastname": "Smith"})
E11000 duplicate key error index: database.users.$_id_  dup key: { : "jsmith" }

But you might have chance to be surprised that the MongoOperations(more precisely, org.springframework.data.mongodb.core.MongoOperations) does not complain even you insert the same object twice in Spring.

As of today, the latest release of spring-data-mongodb
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>1.4.0.RELEASE</version>
</dependency>

The POJO class, User.java
public class User {
 
    @Id
    private String id;
    private String firstname;
    private String lastname;

    public User(String id, String username, String password) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
    }

    getters and setters
    ...
}

The main function
User user = new User("jsmith", "John", "Smith");
mongoOps.insert(user);
User user = new User("jsmith", "John", "Smith");
mongoOps.insert(user);

The code will run with no exception, but only one entry will be inserted. In order to see the "E11000 duplicate key error index" error in Spring, configure mongo with write-concern, e.g. <mongo:mongo host="localhost" port="27017" write-concern="SAFE" />

Then you will see org.springframework.dao.DuplicateKeyException is thrown.

Reference
Where's My Exceptions, Spring Data MongoDB?
MongoDB: No exception when saving duplicate value to an attribute annotated with @Indexed(unique=true)