1

I have a document in MongoDB with unique compound index.

@Document
@CompoundIndex(def = "{'field1':1, 'field2':1", unique = true)
public class MyClass implements Serializable {

    @Id
    private String id;

    private Field1 field1;

    private Field2 field2

...
}

I use Spring Data. Whenever I try to save a document with both values duplicated, I get E11000 duplicate key error with an appropriate Duplicate Key Exception.

I want to make MongoDB replace the record in case of duplication instead of throwing an exception. But both MongoRepository methods like save and insert are of no help. Is there any way to do what I want?

Alesto
  • 639
  • 4
  • 13
  • 29
  • if you want to replace, what is the point in creating an index? You create an index to avoid overwriting – pvpkiran Jun 27 '18 at 08:04
  • Because there are a lot of other fields that may be different, and this index is not a primary key. – Alesto Jun 27 '18 at 08:15

0 Answers0