---
title: UPDATE
slug: v4-6/crud/update
docTags: 
createdAt: 2023-11-14T21:13:44.225Z
---

There are two ways to modify documents in DQL:

::::WorkflowBlock
:::WorkflowBlockItem
`UPDATE`

When executing `UPDATE` to apply changes, only the minimum data necessary to enforce all peers converge on one view of the data sync across the mesh. ([Updating](./#updating))
:::

:::WorkflowBlockItem
`INSERT`

While `INSERT` operations modify all provided fields, even if they remain unchanged. ([Inserting to Update](./#inserting-to-update))
:::
::::

# Updating

To optimize performance and reduce unnecessary overhead, apply most updates in your app through the `UPDATE` method instead.

:::hint{type="info"}
For the full DQL syntax, see *Ditto Query Language&#x20;*> [UPDATE](docId\:yeXrv69KDe-e_XykJR8Mv).
:::

Here is an example of a basic `UPDATE` operation on the `cars` collection:

:::CodeblockTabs
```swift
try await ditto.store.execute("""
  UPDATE cars
  SET color = 'blue'
  WHERE _id = '123'
  """);
```

```kotlin
ditto.store.execute("""
  UPDATE cars
  SET color = 'blue'
  WHERE _id = '123'
  """)
```

```javascript
await ditto.store.execute(`
  UPDATE cars
  SET color = 'blue'
  WHERE _id = '123'`)
```

```java
DittoQueryResult result = (DittoQueryResult) ditto.store.execute(
  "UPDATE cars SET color = 'blue' WHERE _id = '123'",
  new Continuation<>() {
    @NonNull
    @Override
    public CoroutineContext getContext() {
      return EmptyCoroutineContext.INSTANCE;
    }

    @Override
    public void resumeWith(@NonNull Object o) {
      if (o instanceof Result.Failure) {
        // Handle failure
      }
    }
  }
);
```

```csharp
await ditto.Store.ExecuteAsync(
  "UPDATE cars SET color = 'blue' WHERE _id = '123'");
```

```cpp
ditto.get_store().execute(
  "UPDATE cars SET color = 'blue' WHERE _id = '123'").get();
```

```rust
ditto.store().execute(
  "UPDATE cars SET color = 'blue' WHERE _id = '123'",
  None); 
```
:::

## Attachment Token

Once an `ATTACHMENT` object is created and linked to a document, it becomes immutable, meaning its contents cannot be changed.&#x20;

However, you can *indirectly* update attachments by performing an `UPDATE` operation on the document to replace the existing *attachment token* with a different one. The attachment token is the reference pointer linking the document to the attachment's binary data stored separately.&#x20;

:::hint{type="info"}
Before you can access an attachment in your app, you must actively fetch it, unlike a document, which is always readily accessible. For instructions, see [READ](docId\:ySWOINf8JdL-ZdF6OvBgw).
:::

:::CodeblockTabs
```swift
// Updating a Ditto Document with an attachment
// Update the document "123" with a new attachment
try await ditto.store.execute(
    query: """
    UPDATE COLLECTION cars (my_attachment ATTACHMENT)
    SET my_attachment = :newAttachment
    WHERE _id = "123"
    """,
    arguments: ["newAttachment": newAttachment]
)
```

```kotlin
// Updating a Ditto Document with an attachment
// Fetch the document "123" with a new attachment
val query = "SELECT * FROM COLLECTION cars WHERE _id = :id"
val arguments = mapOf("id" to "123") // Assuming the document ID is "123"
val selectQueryResult = runBlocking { ditto.store.execute(query, arguments) }

// Get the existing document
val existingDocument = selectQueryResult.items.firstOrNull()
if (existingDocument != null) {
    // Modify the document, including updating the attachment reference
    val updatedDocument = existingDocument.value.toMutableMap()
    updatedDocument["my_attachment"] = newAttachment // Assuming `newAttachment` is the updated attachment

    // Save the updated document back to the collection
    val updateQuery = "UPDATE COLLECTION cars DOCUMENTS (:document) WHERE _id = :id"
    val updateArguments = mapOf("document" to updatedDocument, "id" to "123") // Assuming the document ID is "123"
    runBlocking { ditto.store.execute(updateQuery, updateArguments) }
} else {
    println("Document not found.")
}
```

```javascript
// Updating a Ditto Document with an attachment
// Update the document "123" with a new attachment
await ditto.store.execute(`
  UPDATE COLLECTION cars (my_attachment ATTACHMENT)
    SET my_attachment = :newAttachment
    WHERE _id = "123"`, 
  { newAttachment })
```

```java
// Updating a Ditto Document with an attachment
// Fetch the document "123" with a new attachment
val query = "SELECT * FROM COLLECTION cars WHERE _id = :id"
val arguments = mapOf("id" to "123") // Assuming the document ID is "123"
val selectQueryResult = runBlocking { ditto.store.execute(query, arguments) }

// Get the existing document
val existingDocument = selectQueryResult.items.firstOrNull()
if (existingDocument != null) {
    // Modify the document, including updating the attachment reference
    val updatedDocument = existingDocument.value.toMutableMap()
    updatedDocument["my_attachment"] = newAttachment // Assuming `newAttachment` is the updated attachment

    // Save the updated document back to the collection
    val updateQuery = "UPDATE COLLECTION cars DOCUMENTS (:document) WHERE _id = :id"
    val updateArguments = mapOf("document" to updatedDocument, "id" to "123") // Assuming the document ID is "123"
    runBlocking { ditto.store.execute(updateQuery, updateArguments) }
} else {
    println("Document not found.")
}
```

```csharp
// Updating a Ditto Document with an attachment
// Update the document "123" with a new attachment
await ditto.Store.ExecuteAsync(
    query: @"
         UPDATE COLLECTION cars (my_attachment ATTACHMENT)
         SET my_attachment = :newAttachment
         WHERE _id = '123'
         ",
    arguments: new Dictionary<string, object>() { { "newAttachment", newAttachment } }
);
```

```rust
// Updating a ditto document with an attachment
    // (update the document "123" with a new attachment)
    peer_a
        .store()
        .execute(
            r#"
            UPDATE COLLECTION cars (my_attachment ATTACHMENT)
            SET my_attachment = :new_attachment
            WHERE _id = "123"
        "#,
            Some(
                json!({
                    "new_attachment": new_attachment,
                })
                .into(),
            ),
        )
        .await?;

    wait_for_id_to_be_present_in(peer_b, "123").await?;
```
:::

## MAP Data Type

To add a `MAP` to a document, use the operator syntax `-> (...)`, allowing you to edit multiple child fields within a single `MAP`:

:::CodeblockTabs
DQL

```sql
UPDATE COLLECTION cars (properties MAP)
SET
  properties -> (
    color = 'red',
    mileage = 3001
  )
WHERE
  _id = '123' 
```
:::

## Multiple Documents

Modify multiple documents simultaneously based on a specified condition.

For example, here is a snippet demonstrating the `UPDATE` operation modifying all documents in the cars collection that are currently red, and changing their color to blue.&#x20;

After the update, you can reference the documents modified by the `mutatedDocumentIDs` method on the `result` of the update.

:::CodeblockTabs
```swift
let result = try await ditto.store.execute(
  "UPDATE cars SET color = 'blue' WHERE _id = '123'");
  
result.mutatedDocumentIDs.forEach() { print($0) }
```

```kotlin
var result = ditto.store.execute("""
  UPDATE cars
  SET color = 'blue'
  WHERE _id = '123'
  """)

result.mutatedDocumentIDs().forEach { id ->
    println(id)
}
```

```javascript
const result = await ditto.store.execute(`
  UPDATE cars
  SET color = 'blue'
  WHERE color = 'red'`)

console.log(result.mutatedDocumentIDs())
```

```java
DittoQueryResult result = (DittoQueryResult) ditto.store.execute(
    "UPDATE cars SET color = 'blue' WHERE color = 'red'",
    new Continuation<>() {
        @NonNull
        @Override
        public CoroutineContext getContext() {
            return EmptyCoroutineContext.INSTANCE;
        }

        @Override
        public void resumeWith(@NonNull Object o) {
            if (o instanceof Result.Failure) {
                // Handle failure
            }
        }
    }
);

for (String id : result.mutatedDocumentIDs()) {
    System.out.println(id);
}
```

```csharp
const result = await ditto.Store.ExecuteAsync(
  "UPDATE cars SET color = 'blue' WHERE color = 'red'");
  
result.MutatedDocumentIDs.ForEach(id => Console.WriteLine(id));
```

```cpp
ditto.get_store().execute(
  "UPDATE cars SET color = 'blue' WHERE color = 'red'").get();
```

```rust
ditto.store().execute(
  "UPDATE cars SET color = 'blue' WHERE color = 'red'",
  None); 
```
:::

# Inserting to Update

The `INSERT` operation provides conflict policy options to override default behavior if a document with the same ID already exists.&#x20;

:::hint{type="info"}
For the full DQL syntax, see *Ditto Query Language&#x20;*> [INSERT](docId:0fqmuBShimf8DwqP-XPa3).
:::

By using the `ON ID CONFLICT DO UPDATE` policy, inserted documents automatically apply updates for all provided fields.

:::hint{type="warning"}
To optimize performance and reduce unnecessary overhead, apply most data modifications in your app through the `UPDATE` method.
:::

:::CodeblockTabs
```swift
var document = [
  "_id": "123",
  "color": "red",
];

try await ditto.store.execute(
  query:"""
  INSERT INTO cars
  DOCUMENTS (:document)
  ON ID CONFLICT DO UPDATE
  """,
  arguments: [ "document": document ]);
```

```kotlin
ditto.store.execute(
  "INSERT INTO cars DOCUMENTS (:car)",
  mapOf("car" to mapOf(
    "_id" to "123",
    "color" to "red"
  )))
```

```javascript
const document = {
  _id: "123",
  color: "red",
}

await ditto.store.execute(`
  INSERT INTO cars
  DOCUMENTS (:document)
  ON ID CONFLICT DO UPDATE`,
  { document })
```

```java
Map<String, String> document = new HashMap<>();
newCar.put("_id", "123");
newCar.put("color", "red");

DittoQueryResult result = (DittoQueryResult) ditto.store.execute(
    "INSERT INTO cars DOCUMENTS (:document) ON ID CONFLICT DO UPDATE",
    Collections.singletonMap("document", document),
    new Continuation<>() {
        @NonNull
        @Override
        public CoroutineContext getContext() {
            return EmptyCoroutineContext.INSTANCE;
        }

        @Override
        public void resumeWith(@NonNull Object o) {
            if (o instanceof Result.Failure) {
                // Handle failure
            }
        }
    }
);
```

```csharp
var args = new Dictionary<string, object> {
  "document", new { _id = "123" , color = "red" }
};

await ditto.Store.ExecuteAsync(
  "INSERT INTO cars"
+ " DOCUMENTS (:document) ON ID CONFLICT DO UPDATE",
  args);
```

```cpp
std::map<std::string, std::map<std::string, std::string>> args;
args["document"] = {{"_id", "123"},{"color", "red"}};

ditto.get_store().execute(
  "INSERT INTO cars DOCUMENTS (:document) ON ID CONFLICT DO UPDATE",
  args).get();
```

```rust
struct Args {
  document: Car,
}
struct Car {
  _id: String,
  color: String
}

// ...

let args = Args {
  document: Car {
    _id: "123".to_string(),
    color: "red".to_string()
  },
};

ditto.store().execute(
  "INSERT INTO cars DOCUMENTS (:document)",
  args); 
```
:::

## MAP in a MAP

If you need to represent and organize highly complex data in a hierarchical structure, consider embedding a `MAP` within another `MAP` to establish a parent-child relationship within a document as follows:

:::CodeblockTabs
```swift
let arguments: [String: Any] = [
  "newDocument": [
    "_id": "123",
    "top_map": [
      "nested_map": [
        "color": "blue"
      ]
    ]
  }
];

await ditto.store.execute(
  query: """
  INSERT INTO COLLECTION your_collection_name (top_map MAP(nested_map MAP))
  DOCUMENTS (:newDocument)
  """,
  arguments: arguments);
```

```kotlin
val arguments = mapOf(
  "newDocument" to mapOf(
    "_id" to "123",
    "top_map" to mapOf(
      "nested_map" to mapOf(
        "color" to "blue"
      )
    )
  )
)

ditto.store.execute("""
  INSERT INTO COLLECTION your_collection_name (top_map MAP(nested_map MAP))
  DOCUMENTS (:newDocument)
  """,
  arguments)
```

```javascript
const newDocument = {
  _id: "123",
  top_map: {
    nested_map: {
      color: "blue"
    }
  }
}

await ditto.store.execute(`
  INSERT INTO COLLECTION your_collection_name (top_map MAP(nested_map MAP))
  DOCUMENTS (:newDocument)`,
  { newDocument });
```

```java
Map<String, Object> nestedMap = new HashMap<>();
nestedMap.put("color", "blue");

Map<String, Object> topMap = new HashMap<>();
topMap.put("nestedMap", nestedMap);

Map<String, Object> newDocument = new HashMap<>();
newDocument.put("_id", "123");
newDocument.put("topMap", topMap);

DittoQueryResult result = (DittoQueryResult) ditto.store.execute(
    "INSERT INTO COLLECTION your_collection_name (top_map MAP(nested_mapMAP)) DOCUMENTS (:newDocument)",
    Collections.singletonMap("newDocument", newDocument),
    new Continuation<>() {
        @NonNull
        @Override
        public CoroutineContext getContext() {
            return EmptyCoroutineContext.INSTANCE;
        }

        @Override
        public void resumeWith(@NonNull Object o) {
            if (o instanceof Result.Failure) {
                // Handle failure
            }
        }
    }
);
```

```csharp
var nestedMap = new {
  color = "blue"
};
var topMap = new {
  nestedMap = nestedMap
};
var args = new Dictionary<string, object>();
args.Add("newDocument", new { _id = newId, topMap = topMap })

var result = await ditto.Store.ExecuteAsync(
  "INSERT INTO COLLECTION your_collection_name (top_map MAP(nested_map MAP))"
+ " DOCUMENTS (:newDocument)",
  args);
```

```cpp
struct NestedMap {
  std::string color;
};
struct TopMap {
  NestedMap nestedMap;
};
struct Document {
  std::string _id;
  TopMap topMap;
};

// ...

std::map<std::string, Document> args;
args["newDocument"] = {"123", TopMap{NestedMap{"blue"}}};

ditto.get_store().execute(
  "INSERT INTO COLLECTION your_collection_name (properties MAP)"
+ " DOCUMENTS (:newDocument)",
  args);
```

```rust
struct Args {
  newDocument: Document,
}
struct NestedMap {
  color: String
}
struct TopMap {
  nestedMap: NestedMap
}
struct Document {
  _id: String,
  topMap: TopMap
}

// ...

let args = Args {
  newDocument: Document {
    _id: "123".to_string(),
    topMap: TopMap {
      nestedMap: NestedMap {
        sobField: "blue".to_string()
      }
    }
  },
};

await ditto.store().execute("
  "INSERT INTO COLLECTION your_collection_name (properties MAP)"
+ " DOCUMENTS (:newDocument)",
  args);
```
:::

