@Indexed annotation ignored when using named collections @Indexed annotation ignored when using named collections mongodb mongodb

@Indexed annotation ignored when using named collections


Unfortunately MongoTemplate function

public void insert(Object objectToSave, String collectionName)

using collectionName only for saving object and not for creating any annotated indexes.If object passed to save operation then application event listener MongoPersistentEntityIndexCreator scan saved entity class for @Indexed annotations and create indexes. But it detect collection name based on next formula (from sources):

String collection = StringUtils.hasText(index.collection()) ? index.collection() : entity.getCollection();

where index.collection() is collection from @Indexed annotation and entity.getCollection() from @Document annotation.

So, you need to call ensureIndex() manually.It's strange behaviour. I think you can open bug here: DATAMONGO

EDIT: I think you can create function that return all classes annotated with @Document and also get all collections from mongodb started from cars.<year>. Then you can analyse all fields annotated with @Indexed and, as result, call ensureIndex for this fields using collections list.


I really need to be able to specify the collection name manually because:

I need to ensure different subclasses of Car end up in the same collectionI would like to store each year's worth of Cars in a separate collection

As for your first statement, you can enforce a single collection using @Document metadata annotation:

@Document(collection="cars")class Car {    @Id    String id ;    @Indexed    String manufacturer ;}@Document(collection="cars")class Honda extends Car {}@Document(collection="cars")class Volvo extends Car {}

The collection field of @Document will take care that every subclass of car gets into the cars collection, plus the index is automatically created with the help of the @Indexed annotation.


You maybe better off stooping to the DB level and checking if the collection has indexes you need using getIndexes and calling the ensureIndex as part of your application start up.

Tip: Implement InitializingBean on the class that configures mongo for your application and do the magic there.

No preaching, IMHO Spring is good at certain things and so-so at others. I try to avoid the bloat other than for DI & TXN management in non XA environments.