[SERVER-14094] Conditional Updates: Conditionally update secondary fields if primary fields updated Created: 30/May/14 Updated: 06/Dec/22 Resolved: 29/Jun/19 |
|
| Status: | Closed |
| Project: | Core Server |
| Component/s: | Write Ops |
| Affects Version/s: | None |
| Fix Version/s: | None |
| Type: | New Feature | Priority: | Major - P3 |
| Reporter: | Kris Brown | Assignee: | Backlog - Query Team (Inactive) |
| Resolution: | Won't Do | Votes: | 3 |
| Labels: | None | ||
| Remaining Estimate: | Not Specified | ||
| Time Spent: | Not Specified | ||
| Original Estimate: | Not Specified | ||
| Issue Links: |
|
||||||||||||
| Assigned Teams: |
Query
|
||||||||||||
| Participants: | |||||||||||||
| Description |
|
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:
More formally: 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). Related information:
|
| Comments |
| Comment by Asya Kamsky [ 29/Jun/19 ] |
|
You can see some examples here. This can be done by using various conditional aggregation expressions. I believe this can handle all of the examples/use cases that were mentioned in the comments. |
| Comment by David Storch [ 07/Mar/16 ] |
|
asya ian.whalen this looks slightly different than |