---
title: CREATE
slug: v4-5/crud-create
docTags: 
createdAt: 2023-07-28T20:02:36.395Z
---

This article provides an overview of creating documents using the `INSERT` DQL operation.

All modification operations in Ditto are performed using the `execute` API method against the `ditto.store`:

:::CodeblockTabs
```swift
let result = try await ditto.store.execute(query: /* query */, arguments: /* arguments */);
```

```kotlin
var result = ditto.store.execute(/* query */, /* arguments */)
```

```javascript
const result = await ditto.store.execute(/* query */, /* arguments */)
```

```java
DittoQueryResult result = (DittoQueryResult) ditto.store.execute(
  /* query */,
  /* arguments */,
  /* continuation */);
```

```csharp
var result = await ditto.Store.ExecuteAsync(/* query */, /* arguments */);
```

```cpp
auto result = ditto.get_store().execute(/* query */, /* arguments */).get();
```

```rust
let result = ditto.store().execute(/* query */, /* arguments */);
```
:::

When writing updates by way of the `execute` API method with `INSERT` operation:

- If the document does *not* exist locally, Ditto creates it. &#x20;

- If the document already exists in the local store, Ditto throws an error.

- If the document is inserted by two or more peers at the same time, the documents that were inserted after the first document will be treated as having performed an `UPDATE` operation for all fields.

# Creating A New Document

:::CodeblockTabs
```swift
await ditto.store.execute(
  query: "INSERT INTO cars DOCUMENTS (:newCar)",
  arguments: ["newCar": ["color": "blue"]]);
```

```kotlin
ditto.store.execute(
  "INSERT INTO cars DOCUMENTS (:newCar)",
  mapOf("newCar" to mapOf("color" to "blue")))
```

```javascript
await ditto.store.execute(
  "INSERT INTO cars DOCUMENTS (:newCar)",
  { newCar: { color: "blue" } });
```

```java
DittoQueryResult result = (DittoQueryResult) ditto.store.execute(
    "INSERT INTO cars DOCUMENTS (:newCar)",
    Collections.singletonMap("newCar", Collections.singletonMap("color", "blue")),
);
```

```csharp
var args = new Dictionary<string, object>();
args.Add("newCar", new { color = "blue" });

await ditto.Store.ExecuteAsync(
  "INSERT INTO cars DOCUMENTS (:newCar)",
  args);
```

```cpp
std::map<std::string, std::map<std::string, std::string>> args;
args["newCar"] = {{"color", "blue"}};

auto result = ditto.get_store().execute(
  "INSERT INTO cars DOCUMENTS (:newCar)",
  args).get();
```

```rust
use serde::Serialize;

#[derive(Serialize)]
struct Args {
  newCar: Car,
}
#[derive(Serialize)]
struct Car {
  color: String
}

// ...

let args = Args {
  newCar: Car {
    color: "blue".to_string()
  },
};

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

For complete DQL syntax, see *Ditto Query Language (DQL)&#x20;*> [INSERT](docId\:poKcNKEX_OxyeJKOAUPTi)

# Creating Multiple Documents

Multiple documents can be created at the same time using the `INSERT` operation.

:::CodeblockTabs
```swift
await ditto.store.execute(
  query: "INSERT INTO cars DOCUMENTS (:car1), (:car2)",
  arguments: [
    "car1": ["color": "blue"],
    "car2": ["color": "red"]
  ]);
```

```kotlin
ditto.store.execute(
  "INSERT INTO cars DOCUMENTS (:car1),(:car2)",
  mapOf(
    "car1" to mapOf("color" to "blue"),
    "car2" to mapOf("color" to "red")
  ))
```

```javascript
await ditto.store.execute(
  "INSERT INTO cars DOCUMENTS (:car1),(:car2)",
  {
    car1: { color: 'blue' },
    car2: { color: 'red' }
  });
```

```java
Map<String, Map<String, String>> args = new HashMap<>();
args.put("car1", Collections.singletonMap("color", "blue"));
args.put("car2", Collections.singletonMap("color", "red"));

DittoQueryResult result = (DittoQueryResult) ditto.store.execute(
    "INSERT INTO cars DOCUMENTS (:car1),(:car2)",
    args,
    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>();
args.Add("car1", new { color = "blue" });
args.Add("car2", new { color = "red" });

await ditto.Store.ExecuteAsync(
  "INSERT INTO cars DOCUMENTS (:car1),(:car2)",
  args);
```

```cpp
std::map<std::string, std::map<std::string, std::string>> args;
args["car1"] = {{"color", "blue"}};
args["car2"] = {{"color", "red"}};

auto result = ditto.get_store().execute(
    "INSERT INTO cars DOCUMENTS (:car1),(:car2)",
    args).get();
```

```rust
use serde::Serialize;

#[derive(Serialize)]
struct Args {
  newCar: Car,
}
#[derive(Serialize)]
struct Car {
  color: String
}

// ...

let args = Args {
  car1: Car {
    color: "blue".to_string()
  },
  car2: Car {
    color: "red".to_string()
  },
};

ditto.store().execute(
  "INSERT INTO cars DOCUMENTS (:car1),(:car2)",
  Some(args.into())); 
```
:::

# New Document Identifiers

When creating a document, unless manually supplied, Ditto automatically generates and assigns the new document a 128‑bit Universally Unique Identifier (UUID).&#x20;

The document identifier is represented as `_id` and is the primary key for the document.

## Automatic ID&#x20;

If an identifier isn't provided Ditto will automatically generate one. This identifier can be accessed on the `result` object using the `mutatedDocumentIDs` field.

:::CodeblockTabs
```swift
let result = await ditto.store.execute(
  query: "INSERT INTO cars DOCUMENTS (:newCar)",
  arguments: [
    newCar: ["color": "blue"]
  ]);

// "507f191e810c19729de860ea"
print(result.mutatedDocumentIDs()[0])
```

```kotlin
var result = ditto.store.execute(
  "INSERT INTO cars DOCUMENTS (:newCar)",
  mapOf("newCar" to mapOf("color" to "blue")))

// "507f191e810c19729de860ea"
println(result.mutatedDocumentIDs().first())
```

```javascript
const result = await ditto.store.execute(
  "INSERT INTO cars DOCUMENTS (:newCar)",
  { newCar: { color: 'blue' } });

// "507f191e810c19729de860ea"
console.log(result.mutatedDocumentIDs()[0])
```

```java
DittoQueryResult result = (DittoQueryResult) ditto.store.execute(
    "INSERT INTO cars DOCUMENTS (:newCar)",
    Collections.singletonMap("newCar", Collections.singletonMap("color", "blue")),
    new Continuation<>() {
        @NonNull
        @Override
        public CoroutineContext getContext() {
            return EmptyCoroutineContext.INSTANCE;
        }

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

// "507f191e810c19729de860ea"
System.out.println(result.mutatedDocumentIDs()[0]);
```

```csharp
var insertArgs = new Dictionary<string, object>();
insertArgs.Add("newCar", new { color = "blue" });

var result = await ditto.Store.ExecuteAsync(
  "INSERT INTO cars DOCUMENTS (:newCar)",
  insertArgs);
  
// "507f191e810c19729de860ea"
result.MutatedDocumentIds.ForEach(id => Console.WriteLine(id));
```

```cpp
std::map<std::string, std::map<std::string, std::string>> args;
args["newCar"] = {{"color", "blue"}};

auto result = ditto.get_store().execute(
  "INSERT INTO cars DOCUMENTS (:newCar)",
  args).get();

// "507f191e810c19729de860ea"
std::cout << result.mutated_document_ids()[0].to_string();
```

```rust
use serde::Serialize;

#[derive(Serialize)]
struct Args {
  newCar: Car,
}
#[derive(Serialize)]
struct Car {
  color: String
}

// ...

let args = Args {
  newCar: Car {
    color: "blue".to_string()
  },
};

let result = ditto.store().execute(
  "INSERT INTO cars DOCUMENTS (:newCar)",
  Some(args.into())); 

// "507f191e810c19729de860ea"
println!("{}", result.mutated_document_ids()[0].to_string())
```
:::

## Supplying a Custom ID

A custom document identifier can be either a string or a JSON-object. JSON-object keys are referred to as *composite identifiers* because multiple sub-fields together represent the identifier.

Document identifiers are immutable and you can only configure it at the time of document creation.&#x20;

Once a document is created, to ensure consistency and uniqueness throughout the platform, the unique identifier that either Ditto automatically generated and assigned or you manually assigned becomes permanent and cannot be changed at a later time.

For more information about document IDs, see *Platform Manual&#x20;*> [Document Model](docId\:CW7AJZtSB92tGeO1O8HMv).

### String ID

For example, the following snippet demonstrates a new document assigned the custom ID `"123"`.

:::CodeblockTabs
```swift
let result = await ditto.store.execute(
  query: "INSERT INTO cars DOCUMENTS (:newCar)",
  arguments: [
    newCar: [ "_id": "123", "color": "blue"]
  ]);

// "123"
print(result.mutatedDocumentIDs()[0])
```

```kotlin
var result = ditto.store.execute(
  "INSERT INTO cars DOCUMENTS (:newCar)",
  mapOf("newCar" to mapOf("_id" to "123", "color" to "blue")))
  
// "507f191e810c19729de860ea"
println(result.mutatedDocumentIDs().first())
```

```javascript
const newCar = {
  _id: "123",
  color: "blue"
}

const result = await ditto.store.execute(`
  INSERT INTO cars
  DOCUMENTS (:newCar)`,
  { newCar });

// "123"
console.log(result.mutatedDocumentIDs()[0])
```

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

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

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

// "123"
System.out.println(result.mutatedDocumentIDs()[0]);
```

```csharp
var insertArgs = new Dictionary<string, object>();
insertArgs.Add("newCar", new { _id = "123", color = "blue" });

var result = await ditto.Store.ExecuteAsync(
  "INSERT INTO your_collection_name DOCUMENTS (:newCar)",
  insertArgs);
  
// "123"
result.MutatedDocumentIds.ForEach(id => Console.WriteLine(id));
```

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

auto result = ditto.get_store().execute(
  "INSERT INTO cars DOCUMENTS (:newCar)",
  args).get();

// "123"
std::cout << result.mutated_document_ids()[0].to_string();
```

```rust
use serde::Serialize;

#[derive(Serialize)]
struct Args {
  newCar: Car,
}
#[derive(Serialize)]
struct Car {
  _id: String,
  color: String
}

// ...

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

let result = ditto.store().execute(
  "INSERT INTO cars DOCUMENTS (:newCar)",
  Some(args.into())); 

// "123"
println!("{}", result.mutated_document_ids()[0].to_string())
```
:::

Following is the new `123` document that results:

:::CodeblockTabs
Ditto Document

```json
{
  "_id": "123",
  "color": "blue"
}
```
:::

### Composite ID

The following snippet demonstrates combining the `vin` and `make` fields to form the composite key:

:::CodeblockTabs
```swift
let arguments = [
  newCar: [ "_id": [vin: "123", make: "Toyota"], "color": "blue"]
];

let result = await ditto.store.execute(
  query: "INSERT INTO cars DOCUMENTS (:newCar)",
  arguments: arguments);

// "{vin: "123", make: "Toyota"}"
print(result.mutatedDocumentIDs()[0])
```

```kotlin
var result = ditto.store.execute(
  "INSERT INTO cars DOCUMENTS (:newCar)",
  mapOf(
    "newCar" to mapOf(
      "_id" to mapOf(
        "vin" to "123",
        "make" to "Toyota"
      ),
      "color" to "blue"
  )))
  
// "{vin: "123", make: "Toyota"}"
println(result.mutatedDocumentIDs().first())
```

```javascript
const newCar = {
  _id: {
    vin: "123",
    make: "Toyota"
  },
  color: "blue"
}
const result = await ditto.store.execute(`
  INSERT INTO cars
  DOCUMENTS (:newCar)`,
  { newCar });

// "{vin: "123", make: "Toyota"}"
console.log(result.mutatedDocumentIDs()[0])
```

```java
Map<String, String> newCarId = new HashMap<>();
newCarId.put("vin", "123");
newCarId.put("make", "Toyota");
Map<String, Object> newCar = new HashMap<>();
newCar.put("_id", newCarId);
newCar.put("color", "blue");

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

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

// "{vin: "123", make: "Toyota"}"
System.out.println(result.mutatedDocumentIDs()[0]);
```

```csharp
var newId = new { vin: "123", make: "Toyota"};
var insertArgs = new Dictionary<string, object>();
insertArgs.Add("newCar", new { _id = newId, color = "blue" });

var result = await ditto.Store.ExecuteAsync(
  "INSERT INTO your_collection_name DOCUMENTS (:newCar)",
  insertArgs);
  
// "{vin: "123", make: "Toyota"}"
result.MutatedDocumentIds.ForEach(id => Console.WriteLine(
  System.Text.Json.JsonSerializer.Serialize(id)));
```

```cpp
struct CarId {
  std::string vin;
  std::string make;
};
struct Car {
  CarId _id;
  std::color String;
};

std::map<std::string, Car> args;
args["newCar"] = {{"123", "Toyota"}, "blue"};

auto result = ditto.get_store().execute(
  "INSERT INTO cars DOCUMENTS (:newCar)",
  args).get();

// "{vin: "123", make: "Toyota"}"
std::cout << result.mutated_document_ids()[0].to_string();
```

```rust
use serde::Serialize;

#[derive(Serialize)]
struct Args {
  newCar: Car,
}
#[derive(Serialize)]
struct CarId {
  vin: String,
  make: String
}
#[derive(Serialize)]
struct Car {
  _id: CarId,
  color: String
}

// ...

let args = Args {
  newCar: Car {
    _id: CarId {
      vin: "123".to_string(),
      make: "Toyota".to_string()
    },
    color: "blue".to_string()
  },
};

let result = ditto.store().execute(
  "INSERT INTO cars DOCUMENTS (:newCar)",
  Some(args.into())); 

// "{vin: "123", make: "Toyota"}"
println!("{}", result.mutated_document_ids()[0].to_string())
```
:::

