Platform Manual
CRUD Operations

Upserting and Updating

This article provides an overview of the Upsert and Update operations:

Key Distinctions



Upsert

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

For instructions on how to create a new document, see Upserting and Updating.

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:

Swift
Kotlin
JS
Java
C#
C++
Rust


Creating New Documents

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:

Swift
Kotlin
JS
Java
C#
C++
Rust


Supplying a Custom ID





For more information about document IDs, see Platform Manual > Document Model.

String ID

For example, the following snippet demonstrates a new document assigned the custom ID abc123.

Swift
Kotlin
JS
Java
C#
C++
Rust


Following is the new abc123 document that results:

JSON


Composite ID

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.

Swift
Kotlin
JS
Java
C#
C++
Rust


Upserting Delta Updates



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:

Swift
Kotlin
JS
Java
C#
C++
Rust


Once executed, the following document is created as a result:

JSON


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":

Swift
Kotlin
JS
Java
C#
C++
Rust


As a result, the color changes to "red"; however, make and year remain the same:

JSON


Update


Swift
Kotlin
JS
Java
C#
C++
Rust


Overview of Behavior by CRDT

Updating an existing document is different depending on the CRDT you're updating: