'Update indexes mongodb using Spring

Does someone know what Spring application properties need to be specified so that the index is overwritten (if already been created) with new parameters.

For example, if I want to change the time of deleting an entry from 1 day to 3 days, Spring cannot compile the project because an index with that name has already been created by a previous run (automatic indexing is enabled).

@Document(collection = 'Item')
class Item {
    @Id
    String id
    @LastModifiedDate
    @Indexed(name='lastModifiedDate', expireAfter = '1d')
    Date lastModifiedDate
    String itemName
}

Spring falls with such an error

Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'mongoTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryDependentConfiguration.class]:
Bean instantiation via factory method failed; 

nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.dao.DataIntegrityViolationException:
Cannot create index for 'lastModifiedDate' in collection 'Item' with keys 'Document{{lastModifiedDate=1}}' and options 'Document{{name=lastModifiedDate, expireAfterSeconds=259200}}'. Index already defined as 'IndexInfo [indexFields=[IndexField [ key: lastModifiedDate, direction: ASC, type: DEFAULT, weight: NaN]], name=lastModifiedDate, unique=false, sparse=false, language=, partialFilterExpression=null, collation=null, expireAfterSeconds=PT24H]'.; 

nested exception is com.mongodb.MongoCommandException:
Command failed with error 85 (IndexOptionsConflict):
'An equivalent index already exists with the same name but different options.
Requested index: { v: 2, key: { lastModifiedDate: 1 }, name: "lastModifiedDate", expireAfterSeconds: 259200 }, existing index: { v: 2, key: { lastModifiedDate: 1 }, name: "lastModifiedDate", expireAfterSeconds: 86400 }' on server localhost:27017. The full response is {"ok": 0.0, "errmsg": "An equivalent index already exists with the same name but different options. Requested index: { v: 2, key: { lastModifiedDate: 1 }, name: \"lastModifiedDate\", expireAfterSeconds: 259200 },
existing index: { v: 2, key: { lastModifiedDate: 1 }, name: \"lastModifiedDate\", expireAfterSeconds: 86400 }", "code": 85, "codeName": "IndexOptionsConflict"}

If you manually remove this index from the database (from the shell), then everything works fine. But every time the parameters change you have to do it manually and you can forget about it. Is there any way to automate this process?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source