Reputation: 2047
I annotate a document with @Index(unique = true) like so:
public class ADocumentWithUniqueIndex {
private static final long serialVersionUID = 1L;
@Indexed(unique = true)
private String iAmUnique;
public String getiAmUnique() {
return iAmUnique;
}
public void setiAmUnique(String iAmUnique) {
this.iAmUnique = iAmUnique;
}
}
When saving the object, I specify a custom collection:
MongoOperations mongoDb = ...
mongoDb.save(document, "MyCollection");
As a result I get:
How can I create the index in "MyCollection" instead without having to explicitly specify it in the annotation?
BACKGROUND:
This seemed like a fairly standard approach to hide the persistence details in a infrastructure component. Any comments on the approach appreciated as well.
Upvotes: 4
Views: 937
Reputation: 83171
It's kind of unusual to define the collection for an object to be stored and then expect the index annotations to work. There's a few options you have here:
Use @Document
on ADocumentWithUniqueIndex
and configure the collection name manually. This will cause all objects of that class to be persisted into that collection of course.
Manually create indexes via MongoOperations.indexOps()
into the collections you'd like to use. This would be more consistent to your approach of manually determining the collection name during persistence operations.
Upvotes: 1