3

I and storing Doc objects in the mongodb repository ensuring that the barcode property is unique across the collection:

@Document(collection = "Doc")
public class Doc {
  @Id  
  private String id;

  @Indexed(unique = true)
  private String barcode;
  ...
}

I also store a DocAudit collection which stores lists of Doc as sub-documents:

@Document(collection = "DocAudit")
public class DocAudit {    
  @Id  
  private String id;

  private List<Doc> docs;
  ...
}

As DocAudit entries are generated, the same Doc can be present in the docs list of two or more DocAudit entries.

The @Indexed(unique = true) on the barcode property of the Doc object is automatically generating mongodb indexes on Doc.barcode (desired) and DocAudit.docs.doc.barcode (undesired)

What's the best way to avoid the automatic generation of the undesired index? Alternatively, what's the best way to remove the undesired index as soon as it is created?

1 Answer 1

1

DocAudit is of course having these properties of Doc, because DocAudit is the inheritor.
To achieve what you want, you may consider one of following:

  • create another Doc without that annotation, then inherited by DocAudit;
  • remove that annotation in Doc, and ensure index for Doc by your independent codes (not recommended);

It's not good to create an index and then drop immediately.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Wizzard. I was hoping there was some magic in spring-data.mongodb that would get around this issue. I have solved the problem by implementing a abstract BaseDoc class without the barcode field and then extending with an indexed barcode field in the actual Doc class. I also created a NestedDoc which extends BaseDoc with the unindexed barcode field. The DocAudit uses the NestedDoc implementation to avoid the undesired index.
@dgb, Technically spring-data-mongodb is able to fulfill your expectation by adding another parameter (such as inheritable) to annotation @Indexed. But still there are other issues, for example one sub-class doesn't want to inherit the feature but another sub-class wants to. Another way may be implemented by creating a new annotation to specify whether or not inheriting specific features from super-class. But it seems that this will complicate code design after several number of hierarchies of inheriting. At last, now your current design is better. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.