Type: New Feature
Priority: Major - P3
Resolution: Won't Do
Affects Version/s: None
Fix Version/s: None
Component/s: Write Ops
Conditionally modify some fields only if “significant” fields are changed during an update.
For example: update the description of a product based on its external identifier (the SKU), and if this would change the document, also modify the updatedBy, updatedAt and version field.
A sample API call for this might be:
For the matching document (or documents if multi:true) if the document exists and applying $set would change the document then apply $set, $setIfModified and $incIfModified.
Note: the timestamps are not the timestamp at which the document will be persisted, but the time at which the request to make the change happened. Therefore $currentDate or ObjectId.getTimestamp() are not suitable in this case.
Workaround: Single Operation
The closest I can get to my requirements using a single call is:
This would allow an application to update the description of a product by an external identifier (the SKU). However, it would result in the updatedBy, updatedAt and version to be modified even if the document already had the same description, which is not the desirable behaviour in this case.
Workaround: Two operations with optimistic locking
Find or create a document matching the query conditions:
Check the returned document to see if applying the primary changes would modify it, and if so, do an update (including the version in the query):
Downside to this is that the version ends up being incremented twice on initial creation. Needs some logic too to check the write results and handle error cases (i.e. version mismatch due to secondary party modifying document between find and update).
- http://docs.mongodb.org/manual/reference/operator/update-field/ - current operators on update
- https://jira.mongodb.org/browse/SERVER-340 - add $setOnInsert
- https://jira.mongodb.org/browse/SERVER-6566 - conditional updates with extra flexibility
- https://jira.mongodb.org/browse/SERVER-13578 - discusses $setOnUpdate and $incOnUpdate with slightly different semantics, but I think these would be better as $*IfModified