Returning both old and new entities from Spring/MongoDB findAndModify
Is there some way to return both old and new entities from findAndModify?
No, there's no way to return both old and new value with findAndModify
.
No, there's no way to return both old and new value with findAndModify.
But if you want to compare entitiy state before and after updating do the below steps
- Just before updating retrieve the data using primary key and store in oldData variable
- in your findAndModify query change returnNew to true to save it under newData
Below sample sudocode will return you both values
public Pair<Data> saveItems(String id, List<Item> items) { final Query findById = ...; final Update update = new Update(); // This is what we actually update update.set(ENTITY_FIELD_ITEMS, newItems); update.inc(ENTITY_FIELD_VERSION, 1); // Try updating and return the old data final Data oldData = findById(); //query to retrieve existing data final Data newData = operations.findAndModify(findById, update, FindAndModifyOptions.options().upsert(true).returnNew(true), Data.class); return new Pair<Data>(oldData, newData); }