> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ditto.live/llms.txt
> Use this file to discover all available pages before exploring further.

# Updating Documents

> This article provides an overview and how-to instructions for updating documents within Ditto.

See [Document Model](/key-concepts/document-model) for more information on documents in Ditto.

There are two ways to modify documents in DQL:

<Steps>
  <Step>
    `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))
  </Step>

  <Step>
    `INSERT`

    While `INSERT` operations modify all provided fields, even if they remain unchanged. ([Inserting](#inserting-with-update))
  </Step>
</Steps>

# Updating

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

<Info>
  For the full DQL syntax, see *Ditto Query Language* [UPDATE](/dql/update).
</Info>

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

<CodeGroup>
  ```swift Swift theme={null}

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

  ```kotlin Kotlin theme={null}
  ditto.store.execute("""
    UPDATE cars
    SET color = 'blue'
    WHERE _id = '123'
    """)
  ```

  ```javascript JS theme={null}
  await ditto.store.execute(`
    UPDATE cars
    SET color = 'blue'
    WHERE _id = '123'`
  );
  ```

  ```typescript TypeScript theme={null}
  await ditto.store.execute(`
    UPDATE cars
    SET color = 'blue'
    WHERE _id = '123'`
  );
  ```

  ```java Java theme={null}
  // This try-with-resources block auto-closes the DittoQueryResult
  try (DittoQueryResult result = ditto.getStore().execute(
          "UPDATE cars SET color = 'blue' WHERE _id = '123'"
      ).toCompletableFuture().join()) {
      ...
  }
  ```

  ```csharp C# theme={null}
  await ditto.Store.ExecuteAsync(
    "UPDATE cars SET color = 'blue' WHERE _id = '123'");
  ```

  ```cpp C++ theme={null}
  ditto.get_store().execute(
    "UPDATE cars SET color = 'blue' WHERE _id = '123'");
  ```

  ```rust Rust theme={null}
  ditto.store().execute(
    "UPDATE cars SET color = 'blue' WHERE _id = '123'",
  ).await?;
  ```

  ```dart Dart theme={null}
  await ditto.store.execute("""
    UPDATE cars
    SET color = 'blue'
    WHERE _id = '123'
  """);
  ```

  ```go Go theme={null}
  result, err = dit.Store().Execute(
  	"UPDATE cars SET color = 'blue' WHERE _id = '123'")
  if err != nil {
      return err
  }
  defer result.Close()  // cleanup
  ```
</CodeGroup>

## MAP Data Type

To add a `MAP` to a document, use the dot syntax, which allows you to edit multiple child fields within a single `MAP`:

<CodeGroup>
  ```sql DQL theme={null}
  UPDATE COLLECTION cars (properties MAP)
  SET
    properties.color = 'red',
    properties.mileage = 3001
  WHERE
    _id = '123'
  ```
</CodeGroup>

## 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.

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

<CodeGroup>
  ```swift Swift theme={null}

  let result = try await ditto.store.execute(
    "UPDATE cars SET color = 'blue' WHERE _id = '123'");

  result.mutatedDocumentIDs.forEach() { print($0) }
  ```

  ```kotlin Kotlin theme={null}
  ditto.store.execute("""
    UPDATE cars
    SET color = 'blue'
    WHERE _id = '123'
    """).use { result ->

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

  ```javascript JS theme={null}
  const result = await ditto.store.execute(`
    UPDATE cars
    SET color = 'blue'
    WHERE color = 'red'`
  );

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

  ```typescript TypeScript theme={null}
  import { QueryResult } from '@dittolive/ditto';

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

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

  ```java Java theme={null}
  // This try-with-resources block auto-closes the DittoQueryResult
  try (DittoQueryResult result = ditto.getStore().execute((
      "UPDATE cars SET color = 'blue' WHERE color = 'red'").toCompletableFuture().join()) {
      for (DittoCborSerializable id : result.getMutatedDocumentIds()) {
          System.out.println(id.asString());
      }
  }
  ```

  ```csharp C# theme={null}
  using var result = await ditto.Store.ExecuteAsync(
    "UPDATE cars SET color = 'blue' WHERE color = 'red'");

  result.MutatedDocumentIDs.ForEach(id => Console.WriteLine(id));
  ```

  ```cpp C++ theme={null}
  ditto.get_store().execute(
    "UPDATE cars SET color = 'blue' WHERE color = 'red'");
  ```

  ```rust Rust theme={null}
  ditto.store().execute(
    "UPDATE cars SET color = 'blue' WHERE color = 'red'",
  ).await?;
  ```

  ```dart Dart theme={null}
  await ditto.store.execute("""
    UPDATE cars
    SET color = 'blue'
    WHERE color = 'red'
  """);
  ```

  ```go Go theme={null}
  result, err := ditto.Store().Execute(
  	"UPDATE cars SET color = :newColor WHERE color = :oldColor",
  	ditto.QueryArguments{
  		"newColor": "blue",
  		"oldColor": "red",
  	},
  )
  if err != nil {
      return err
  }
  defer result.Close()  // cleanup

  for _, id := range result.MutatedDocumentIDs() {
  	log.Printf("%s", id)
  }
  ```
</CodeGroup>

# Inserting with UPDATE

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

<Info>
  For the full DQL syntax, see *Ditto Query Language* [INSERT](/dql/insert).
</Info>

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

<Warning>
  To optimize performance and reduce unnecessary overhead, apply most data modifications in your app through the `UPDATE` method.
</Warning>

<CodeGroup>
  ```swift Swift theme={null}

  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 Kotlin theme={null}
  ditto.store.execute(
    "INSERT INTO cars DOCUMENTS (:car) ON ID CONFLICT DO UPDATE",
    mapOf("car" to mapOf(
      "_id" to "123",
      "color" to "red"
    )))
  ```

  ```javascript JS theme={null}
  const document = {
    _id: "123",
    color: "red",
  };

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

  ```typescript TypeScript theme={null}
  interface Car {
    _id: string;
    color: string;
  }

  const document: Car = {
    _id: "123",
    color: "red",
  };

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

  ```java Java theme={null}
  import static com.ditto.java.serialization.DittoCborSerializable.buildDictionary;

  var document = buildDictionary()
      .put("_id", "123")
      .put("color", "red")
      .build();

  // This try-with-resources block auto-closes the DittoQueryResult
  try (DittoQueryResult result = ditto.getStore().execute(
          "INSERT INTO cars VALUES (:document) ON ID CONFLICT DO MERGE",
          buildDictionary().put("document", document).build()
      ).toCompletableFuture().join()) {
      ...
  }
  ```

  ```csharp C# theme={null}
  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 C++ theme={null}
  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);
  ```

  ```rust Rust theme={null}
  #[derive(Serialize)]
  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) ON ID CONFLICT DO UPDATE",
    args,
  )).await?;
  ```

  ```dart Dart theme={null}
  final document = {
    "_id": "123",
    "color": "red",
  };

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

  ```go Go theme={null}
  result, err = ditto.Store().Execute(
  	"INSERT INTO cars DOCUMENTS (:document) ON ID CONFLICT DO UPDATE",
  	ditto.QueryArguments{
  		"document": ditto.Document{
  			"_id":   "123",
  			"color": "red",
  		},
  	},
  )
  if err != nil {
      return err
  }
  defer result.Close()  // cleanup
  ```
</CodeGroup>

## Nested MAPs

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.

In 4.11+ with `DQL_STRICT_MODE=false`, collection definitions are no longer required.

[Read more about strict mode.](/dql/strict-mode)

```
ALTER SYSTEM SET DQL_STRICT_MODE=false
```

Once Strict Mode is disabled, you can use the `INSERT` operation to add a new document with a nested map structure.

<CodeGroup>
  ```swift Swift theme={null}

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

  await ditto.store.execute(
    query: """
    INSERT INTO your_collection_name
    VALUES (:newDocument)
    """,
    arguments: arguments);
  ```

  ```kotlin Kotlin theme={null}
  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 your_collection_name
    VALUES (:newDocument)
    """,
    arguments)
  ```

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

  await ditto.store.execute(`
    INSERT INTO your_collection_name
    VALUES (:newDocument)`,
    { newDocument }
  );
  ```

  ```typescript TypeScript theme={null}
  interface NestedMap {
    color: string;
  }

  interface TopMap {
    nested_map: NestedMap;
  }

  interface Document {
    _id: string;
    top_map: TopMap;
  }

  const newDocument: Document = {
    _id: "123",
    top_map: {
      nested_map: {
        color: "blue"
      }
    }
  };

  await ditto.store.execute(`
    INSERT INTO your_collection_name
    VALUES (:newDocument)`,
    { newDocument }
  );
  ```

  ```java Java theme={null}
  import static com.ditto.java.serialization.DittoCborSerializable.buildDictionary;

  var nestedMap = buildDictionary()
      .put("color", "blue")
      .build();

  var topMap = buildDictionary()
      .put("nestedMap", nestedMap)
      .build();

  var newDocument = buildDictionary()
      .put("_id", "123")
      .put("topMap", topMap)
      .build();

  // This try-with-resources block auto-closes the DittoQueryResult
  try (DittoQueryResult result = ditto.getStore().execute(
          "INSERT INTO your_collection_name VALUES (:newDocument)",
          buildDictionary().put("newDocument", newDocument).build()
      ).toCompletableFuture().join()) {
      ...
  }
  ```

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

  using var result = await ditto.Store.ExecuteAsync(
  "INSERT INTO your_collection_name "
  + " VALUES (:newDocument)",
  args);
  ```

  ```cpp C++ theme={null}
  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 your_collection_name"
  + " VALUES (:newDocument)",
  args);
  ```

  ```rust Rust theme={null}
  #[derive(Serialize)]
  struct Args {
      newDocument: Document,
  }

  #[derive(Serialize)]
  struct Document {
      _id: String,
      topMap: TopMap
  }

  #[derive(Serialize)]
  struct TopMap {
      nestedMap: NestedMap
  }

  #[derive(Serialize)]
  struct NestedMap {
      color: String
  }

  // ...

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

  ditto.store().execute(
      "INSERT INTO your_collection_name VALUES (:newDocument)",
      args,
  ).await?;
  ```

  ```dart Dart theme={null}
  final newDocument = {
    "_id": "123",
    "top_map": {
      "nested_map": {
        "color": "blue",
      },
    },
  };

  await ditto.store.execute("""
    INSERT INTO your_collection_name
    VALUES (:newDocument)""",
    arguments: {"newDocument": newDocument},
  );
  ```

  ```go Go theme={null}
  result, err := ditto.Store().Execute(
  	"INSERT INTO your_collection_name VALUES (:newDocument)",
  	ditto.QueryArguments{
  		"newDocument": ditto.Document{
  			"_id": "123",
  			"top_map": map[string]any{
  				"nested_map": map[string]any{
  					"color": "blue",
  				},
  			},
  		},
  	},
  )
  if err != nil {
      return err
  }
  defer result.Close()  // cleanup
  ```
</CodeGroup>
