Upserting and Updating
This article provides an overview of the Upsert and Update operations:
Use the Upsert method to achieve any of the following:
- Making changes only to targeted fields
- Creating a new document
- Configuring a custom document ID
The following snippet provides the standard upsert syntax, consisting of the document object that you want to upsert and the options you want to set for the upsert:
When writing updates by way of the Upsert function:
- If the document already exists, Ditto updates the document with the delta changes.
- If the document does not exist, Ditto automatically creates one.
If not manually supplied, Ditto automatically assigns the new document a unique ID as follows:
For more information about document IDs, see Platform Manual > Document Model.
For example, the following snippet demonstrates a new document assigned the custom ID abc123.
Following is the new abc123 document that results:
The following snippet demonstrates combining the user_id and work_id fields to form the 456abc789 composite key:
To mitigate the risk of human error when working with composite keys during write operations, it is recommended to use no more than three fields to form your key.
Using the upsert method to update data can cause performance to degrade. To optimize performance and reduce unnecessary overhead, apply most updates in your app through the update method instead. For more information, see Optimizations.
For example, imagine you create the following document in the cars collection:
Once executed, the following document is created as a result:
When you upsert changes, only the fields you supplied will be modified; existing fields remain unchanged. For instance, consider the following Upsert in which you change the color "blue" to "red":
As a result, the color changes to "red"; however, make and year remain the same:
Updating an existing document is different depending on the CRDT you're updating: