Reputation: 135
I would like to create a very simple annotated java POJO and save it into mongodb. Basically, it is:
@Component("vehicle")
@Scope("prototype")
@Document(collection = "vehicle")
@CompoundIndexes({
@CompoundIndex(name = "plateNumber_idx", def = "{ 'plateNumber' : 1 }", unique = true),
@CompoundIndex(name = "vin_idx", def = "{ 'vin' : 1 }", unique = true),
@CompoundIndex(name = "motorNumber_idx", def = "{ 'motorNumber' : 1 }", unique = true)
})
public class Vehicle {
private String plateNumber;
private String vin;
private String motorNumber;
... getters, setters, equal, hash etc. ....
}
It is working properly, but in my case I need to add a partial index to motorNumber field. The reason is: not necessary fill this field in, therefore this field can be null. But the other hand, not allowed to be two or more similar motorNumber - except, when those are null. I can add partial index(s) to vehicle collection by hand, but it will be more elegant way to do it by annotations. For example, here is my partial index:
{"motorNumber" : {"$exists" : true}}
My question is: How can I add this option to @CompoundIndex ? Or there are any other options ?
Upvotes: 3
Views: 5674
Reputation: 593
I found your question while trying to do much the same thing.
As far as I can tell, neither spring-data-mongodb for spring-boot 1.5.x or 2.0.x supports Partial Indexes via the usual annotations.
However, spring-data-mongodb does allow you to create them programatically:
Index myIndex = new Index()
.background()
.unique()
.named("my_index_name")
.on("indexed_field_1", Sort.Direction.ASC)
.on("indexed_field_2", Sort.Direction.DESC)
.partial(PartialIndexFilter.of(
Criteria.where("criteria_field_1")
.is("BAR")));
DefaultIndexOperations indexOperations = new DefaultIndexOperations(mongoTemplate, "my_collection");
indexOperations.ensureIndex(myIndex);
Upvotes: 7