I have a pojo which looks as following:
@Document
public class MyPojo {
@Id
private String id;
...
@CreatedDate
private ZonedDateTime createdAt;
@LastModifiedDate
private ZonedDateTime modifiedAt;
}
I want to upsert a document with the following logic:
- if the document is new, both
createdAtandmodifiedAtare set tonow. - if the document already exists,
createdAtshould not be updated andmodifiedAtshould be set tonow.
I tried with the following code:
MongoTemplate template = ...; // wired
MyPojo obj = new MyPojo();
template.findAndReplace(
new Query().addCriteria(...),
obj,
new FindAndReplaceOptions().upsert());
Here, the members id, createdAt and modifiedAt are not set (hence they are null).
This does not seem to work. The corresponding fields in the document BSON in the database are never set.
How do you upsert a document in combination with the @CreatedDate and @LastModifiedDate annotations? Is this possible, or do I need to roll out something of my own. In case of the latter, how can I achieve the upsert logic as stated above?
I am using the following configuration:
@Configuration
@EnableMongoAuditing(dateTimeProviderRef = "dateTimeConverter")
Here, dateTimeProviderRef is used to support ZonedDateTime objects.
Also, I noticed that when calling template.save(obj) or template.insert(obj) instead of findAndReplace(...) (as in my code snippet), the createdAt and modifiedAt are set upon creation, as expected. That said, I believe I need findAndReplace(), because I need an atomic upsert to happen.