I am working with Spring-Data/MongoDB and am properly catching duplicate keys upon a save/insert.
As an example, let's say I have a User being saved to a Collection. The User object is annotated with two @Indexed(unique=true) (two unique keys). Let's say they are 'email' and 'username'. How do I retrieve which index was actually duplicated during the insert process.
The closest I get is when I execute this type of example code:
public boolean createNewUser() {
MongoTemplate operations = RepositoryFactory.getMongoOperationsInstance();
try {
log.debug("Saving new user to DB");
operations.save(this);
return true;
} catch (DuplicateKeyException dke) {
log.debug("User with same username or email found");
log.debug(operations.getDb().getLastError());
return false;
}
}
This prints the String:
{ "serverUsed" : "/127.0.0.1:27017" , "err" : "E11000 duplicate key error index: Collection.user.$username dup key: { : \"user\" }" , "code" : 11000 , "n" : 0 , "connectionId" : 17 , "ok" : 1.0}
Without silly String manipulation or a Json conversion, is there a way to extract the Collection.user.$username via the Mongodriver API?
I have been searching unsuccessfully.