How to get which @Indexed(unique=true) is failed in spring-data-mongodb

Viewed 4634

I am using Spring-Boot 1.5.1 and MongoDB 3.4.6

I've a MongoDB document which has some @Indexed(unique=true) annotation on some field.

@Document(collection="Product")
public class Product{
    @Id
    private String id;
    @Indexed(unique=true)
    private String name;
    @Indexed(unique=true)
    private String searchName;

When there is any duplicate name or searchName it throws org.springframework.dao.DuplicateKeyException.

Stacktrace :

Caused by: org.springframework.dao.DuplicateKeyException: E11000 duplicate key error index: Product.name  dup key: { : "name" }; nested exception is com.mongodb.MongoException$DuplicateKey: E11000 duplicate key error index: Product.name dup key: { : "name" }
at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:52)

How can we get the key on which the the exception was thrown.

Something like when we put @NotNull(message = "Product briefDescription cannot be null") on some filed and it gives you the message in the exception, but there is no message attribute for @Indexed annotation.

Any way to do it?

3 Answers

The exception message has the information that you're asking for, it includes both the name of the index for which the error was thrown (in your case Product.name or Product.searchName).

Unfortunately you'll have to parse that information out of the message. This limitation has been raised elsewhere:

Robustly retrieve which field caued 'duplicate key error' in Mongo

And in the following JIRA tickets:

However, in your example (with the duplicate being the null), I would strongly suggest that you push as much validation as possible down at the client level and not rely on the database to handle any validations that can be done at the client.

As far as I know you can't get the key of the duplicate document directly in the error as it's not a core functionality of the Mongo driver. Your best bet would probably be to do a find operation on your collection if the duplicate key exception is raised. You might consider opening a ticket on the Mongo Jira to see if the dev team is interested in adding such a functionality in the future though.

discover operation on your accumulation if the copy key special case is raised. On the off chance that you need to see the genuine keys for a record,query the system.indexes like:

db.collection('system.indexes').findOne({ ns: 'mean-dev.users', name: 'username_1' }, cb);
Related