[SERVER-42084] Easy syntax for $setIfModified behavior Created: 04/Jul/19 Updated: 06/Dec/22 |
|
| Status: | Backlog |
| Project: | Core Server |
| Component/s: | Write Ops |
| Affects Version/s: | 4.2.0 |
| Fix Version/s: | None |
| Type: | Improvement | Priority: | Major - P3 |
| Reporter: | Ben Rotz | Assignee: | Backlog - Query Optimization |
| Resolution: | Unresolved | Votes: | 12 |
| Labels: | None | ||
| Remaining Estimate: | Not Specified | ||
| Time Spent: | Not Specified | ||
| Original Estimate: | Not Specified | ||
| Issue Links: |
|
||||||||
| Assigned Teams: |
Query Optimization
|
||||||||
| Participants: | |||||||||
| Case: | (copied to CRM) | ||||||||
| Description |
|
see Example
You can see that as the complexity of the document grows, the more verbose the command becomes to get this behavior. It would be nice to get this behavior with an easy to use operator (e.g. $setIfModified) |
| Comments |
| Comment by Richard Scarrott [ 12/Apr/22 ] | |||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
I just found out the hard way that aggregation $set is nothing like a regular $set update so as an FYI to anybody else considering using the above code, it's worth first knowing the following two updates are VERY different:
This (https://mongoplayground.net/p/Iw9e1UaTyue):
Is NOTHING like this (https://mongoplayground.net/p/-KQKL2L6Q0w):
The docs say: The $set stage is an alias for $addFields. So this behaviour is weird in the context of an update... but documented. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Comment by Asya Kamsky [ 23/Jul/21 ] | |||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
The code given as example in the description isn't quite correct (it sets updatedAt after the fields are updated which means the updatedAt field will never get set. It turns out there is simpler syntax available to check if that field needs to be set. Assumption: new fields to be set are in document newDoc and in my example it is {{ a:1, b:10 }}. Assuming we are updating document with _id equal to 1:
The first time I run this on existing document which needs to be updated I get an update with resultant doc being:
The second time I run it the update is a no-op. |