Home > other >  I want to get the findAndModify return value of MongoTemplate as a modified value
I want to get the findAndModify return value of MongoTemplate as a modified value

Time:11-12

I am currently using mongoTemplate in Spring boot like this:

public MyEntity update(MyDto dto) {
    ...
    MyEntity result = mongoTemplate.findAndModify(
        query, update, MyEntity.class);

    return result;
}

query puts in the Criteria that finds the MyEntity to be modified, and update puts the contents to change. However, the returned value is the data before the update. How can I get the modified value right away?

CodePudding user response:

When using findAndModify on the mongoTemplate, you have to explicitly configure it if the updated record shall be returned instead of the original one.

This may be done the following way:

FindAndModifyOptions findAndModifyOptions = FindAndModifyOptions.options().returnNew(true);
MyEntity result = mongoTemplate.findAndModify(query, update, findAndModifyOptions, MyEntity.class);

return result;

https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/

  • Related