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

This article provides how-to instructions for creating and organizing documents, linking them to associated files, called *attachments*, and creating `MAP` structures for additional document hierarchies.

Attachments in Ditto are represented using the `ATTACHMENT` data type, which you can use to store binary data, such as images, alongside queryable descriptive information, such as file name and description.&#x20;

# Database Operations

Syncing data across the mesh is an entirely separate process from CRUD, involving replicating documents across different databases rather than interacting with a single datastore.&#x20;

# Creating Documents

To create a document, call the `EXECUTE` API method against the `ditto.store` object and include an `INSERT INTO` query that specifies the document to be inserted.

:::hint{type="info"}
Ditto does *not* support nesting documents within documents. Instead, opt for a foreign-key relationship by referencing the document ID. For more information, see [Relationships](docId\:hZs9xPJv6swbOv5j3Bjoc).
:::

For example, the following snippet demonstrates how to insert a new document with a single field `"color"` set to `"blue"`:

:::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())); 
```
:::

To create multiple documents efficiently, batch your `CREATE` operations in a single operation.

If desired, supply a document ID in your creation request; otherwise, Ditto automatically generates and assigns one.&#x20;

## Inserting Multiple Documents

To create multiple documents in a single operation, use the `INSERT INTO` operation as follows:

:::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())); 
```
:::

## Identifying Documents

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 serves as the primary key for the document.

### Retrieving Document IDs

To access the IDs of the documents affected by the `INSERTION INTO` operation, call the `mutatedDocumentIDs` method on the `result`  object after the insertion like this:&#x20;

:::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 String IDs

When creating a document, you can assign it a custom ID. This custom ID can be generated using a single string value or a combination of two or more string values.&#x20;

This flexibility in structuring document identifiers allows you to customize document IDs to your specific requirements, use cases, or standard naming conventions.&#x20;

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

### Forming Composite Keys

The following 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())
```
:::

# Creating Attachments

There are two separate steps in the process of creating an attachment:

::::WorkflowBlock
:::WorkflowBlockItem
Generate the attachment in the Ditto store. ([Initiating an ATTACHMENT Object](./#initiating-attachment-objects))
:::

:::WorkflowBlockItem
Reference the returned attachment token in a document. ([Referencing an Attachment Token)](./#referencing-attachment-tokens)
:::
::::

:::hint{type="info"}
For a realworld usage scenario, see either the demo chat app for iOS or Android in the getditto > [demoapp-chat](https://github.com/getditto/demoapp-chat/tree/main) GitHub repository.&#x20;
:::

## Initiating ATTACHMENT Objects

To create the `ATTACHMENT` object that encodes your attachment data, call the `newAttachment` method on the`store`namespace.

::::ExpandableHeading
When creating an attachment...

:::hint{type="warning"}
When creating an attachment, provide a valid path to the large file or deeply embedded document you want to encode as an `ATTACHMENT`.  Failure to do so may result in errors related to input-output (IO) operations.&#x20;
:::

:::hint{type="info"}
Creating an attachment in the local Ditto store from data is currently only available in the Ditto SDK for JavaScript.
:::

:::hint{type="info"}
To use a DQL type other than a `REGISTER` — the default data type in Ditto — you must explicitly specify the type in your query; otherwise, Ditto defaults to the `REGISTER` type as follows.&#x20;
:::
::::

If desired, enclose extra information about the attachment, such as name and description. This metadata is useful for attachment fetching operations. &#x20;

:::CodeblockTabs
```swift
let newAttachment = try await ditto.store.newAttachment(path: filePath)
```

```kotlin
```

```javascript
const newAttachment = await ditto.store.newAttachment(filePathOrData)
```

```java
```

```csharp
// snippet currently unavailable.
```

```cpp
```

```rust
use ::dittolive_ditto::prelude::*;
use ::serde_json::json;
use ::std::{collections::HashMap, path::Path};
use serde::Serialize;

async fn attachment_doc_snippet(
    peer_a: &Ditto,
    peer_b: &Ditto,
    filepath: &Path,
) -> Result<(), Error> {
    // Creating an attachment in the local ditto store from a file:
    let new_attachment = peer_a
        .store()
        .new_attachment(filepath, <_>::default())
        .await?;
```
:::

### Adding Optional Metadata

If you want to include information about the attachment, such as name, description, and other relevant details, enclose it in a `metadata` object as key-value pairs.&#x20;

:::CodeblockTabs
```swift
let metadata = ["name": "image.png"]
let newAttachmentWithMetadata = try await ditto.store.newAttachment(path: filePath, metadata: metadata)
```

```kotlin
val attachmentMetadata = mapOf("name" to attachmentFileName)
val attachment = runBlocking { ditto.store.newAttachment(attachmentPathOrInputStream, attachmentMetadata) }
```

```javascript
const metadata = { name: 'image.png' }
const newAttachment = await ditto.store.newAttachment(imageBytes, metadata)
```

```java
val attachmentMetadata = mapOf("name" to attachmentFileName)
val attachment = runBlocking { ditto.store.newAttachment(attachmentPathOrInputStream, attachmentMetadata) }
```

```csharp
// Creating an Attachment in the local Ditto Store from a file:
var newAttachment = await ditto.Store.NewAttachmentAsync(path: filePath);

// Using the optional `metadata` parameter to store arbitrary metadata with the attachment
var metadata = new Dictionary<string, string>()
{
    { "name", "image.png" }
};
var newAttachmentWithMetadata = await Ditto.Store.NewAttachmentAsync(filePath, metadata);

// Creating a Ditto Document with an Attachment
// Create a new document object and store the attachment on the `my_attachment` field.
var newDocument = new Dictionary<string, object>()
{
    { "_id", "123" },
    { "my_attachment", newAttachment }
};
```

```rust
// Using the optional `metadata` parameter to store arbitrary metadata with the attachment
let user_data = HashMap::from_iter([
    ("name".into(), "image.png".into()),
    // Idea: attach a small "summary" of the file contents to preview them in
    // the UI so that the user has some idea of what to "download"/_fetch_.
    //
    // For a text file, it could be some title or the first words of it.
    // For an image, it could be a base64-encoded thumbnail.
    (
        "thumbnail".into(),
        "/9j/4atg9y_zw0ga_x_bzd_w0g_zg9sb...".into(),
    ),
]);
```
:::

For example, in the following snippet, the `metadata` property encapsulates the `name` of the attachment, as well as its `description`:

:::CodeblockTabs
```swift
val attachmentMetadata = mapOf(
    "name" to "Japan",
    "description" to "This is an image of a sunset in Japan."
)
val attachment = runBlocking { ditto.store.newAttachment(attachmentPathOrInputStream, attachmentMetadata) }
```

```kotlin
val attachmentMetadata = mapOf("name" to "Japan")
val attachment = runBlocking { ditto.store.newAttachment(attachmentPathOrInputStream, attachmentMetadata) }
```

```javascript
// Attachment data from Base64 encoded image to bytes
const imageBase64 = 'iVBORw0KGgoAAAANSUhEUgAAAQAAAAEAAQMAAABmvDolAAAAA1BMVEW10NBjBBbqAAAAH0lEQVRoge3BAQ0AAADCoPdPbQ43oAAAAAAAAAAAvg0hAAABmmDh1QAAAABJRU5ErkJggg=='
const imageBytes = Uint8Array.from(imageBase64, (character) => character.charCodeAt(0))

// Using the optional `metadata` parameter to store arbitrary metadata with the attachment
const metadata = { 
    name: 'japan.png', 
    description: 'This is an image of a sunset in Japan.' 
}
const newAttachment = await ditto.store.newAttachment(imageBytes, metadata)
```

```java
val attachmentMetadata = mapOf(
    "name" to "Japan",
    "description" to "This is an image of a sunset in Japan."
)
val attachment = runBlocking { ditto.store.newAttachment(attachmentPathOrInputStream, attachmentMetadata) }
```

```csharp
// Creating an Attachment in the local Ditto Store from a file:
var newAttachment = await ditto.Store.NewAttachmentAsync(path: filePath);

// Using the optional `metadata` parameter to store arbitrary metadata with the attachment
var metadata = new Dictionary<string, string>()
{
    { "name", "image.png" },
    { "description", "This is a picture of a sunset in Japan" }
};
var newAttachmentWithMetadata = await Ditto.Store.NewAttachmentAsync(filePath, metadata);
```

```rust
// Using the optional `metadata` parameter to store arbitrary metadata with the attachment
let user_data = HashMap::from_iter([
    ("name".into(), "japan.png".into()),
    (
        "thumbnail".into(),
        "/9j/4atg9y_zw0ga_x_bzd_w0g_zg9sb...".into(),
    ),
    (
        "description".into(), 
        "This is an image of a sunset in Japan".into()
    ),        
]);

let _new_attachment_with_metadata = peer_a.store().new_attachment(filepath, user_data).await?;
```
:::

## Referencing Attachment Tokens

After creating and storing a new attachment object in Ditto, you receive an *attachment token* as part of the response.

:::ExpandableHeading
An attachment token is...

An attachment token is a pointer that references its associated `ATTACHMENT` object. This token is how you interact with the attachment, such as when fetching or linking it with a document.
:::

The following snippet demonstrates how to create a new document object containing a new attachment, and then insert it into the `cars` collection:

:::CodeblockTabs
```swift
// Create a new document object and store the attachment on the `my_attachment` field.
let newDocument: [String: Any] = ["_id": "123", "my_attachment": newAttachment]

// Insert the new document into the collection
// Note that the `my_attachment` field needs to be declared as an `ATTACHMENT` data type
try await ditto.store.execute(
    query: """
        INSERT INTO COLLECTION cars (my_attachment ATTACHMENT)
        DOCUMENTS (:newDocument)
    """,
    arguments: ["newDocument": newDocument]
)
```

```kotlin
// Create a new document object and store the attachment on the `my_attachment` field.
val document = mapOf("some" to "string", "my_attachment" to attachment)
val insertQuery = "INSERT INTO COLLECTION cars (my_attachment ATTACHMENT) DOCUMENTS (:document)"

// Insert the new document into the collection
// Note that the `my_attachment` field needs to be declared as an `ATTACHMENT` data type
val insertQuery = "INSERT INTO COLLECTION cars (my_attachment ATTACHMENT) DOCUMENTS (:document)"
val insertArguments = mapOf("document" to document)
val insertQueryResult = runBlocking { ditto.store.execute(insertQuery, insertArguments) }
```

```javascript
// Create a new document object and store the attachment on the `my_attachment` field.
const newDocument = { _id: "123", my_attachment: newAttachment }

// Insert the new document into the collection
// Note that the `my_attachment` field needs to be defined as an ATTACHMENT data type
await ditto.store.execute(`
  INSERT INTO COLLECTION cars (my_attachment ATTACHMENT)
  DOCUMENTS (:newDocument)`,
  { newDocument })
```

```java
// Create a new document object and store the attachment on the `my_attachment` field.
val document = mapOf("some" to "string", "my_attachment" to attachment)
val insertQuery = "INSERT INTO COLLECTION cars (my_attachment ATTACHMENT) DOCUMENTS (:document)"

// Insert the new document into the collection
// Note that the `my_attachment` field needs to be declared as an `ATTACHMENT` data type
val insertQuery = "INSERT INTO COLLECTION cars (my_attachment ATTACHMENT) DOCUMENTS (:document)"
val insertArguments = mapOf("document" to document)
val insertQueryResult = runBlocking { ditto.store.execute(insertQuery, insertArguments) }
```

```csharp
// Creating a Ditto Document with an Attachment
// Create a new document object and store the attachment on the `my_attachment` field.
var newDocument = new Dictionary<string, object>()
{
    { "_id", "123" },
    { "my_attachment", newAttachment }
};

// Insert the new document into the collection
// Note that the `my_attachment` field needs to be declared as an `ATTACHMENT` data type
await ditto.Store.ExecuteAsync(
    query: @"
         INSERT INTO COLLECTION cars (my_attachment ATTACHMENT)
         DOCUMENTS (:newDocument)
         ",
    arguments: new Dictionary<string, object>() { { "newDocument", newDocument } }
);
```

```rust
// Creating a Ditto document with an attachment
let new_document /*: impl Serialize */ = json!({
    "_id": "123",
    "my_attachment": new_attachment,
});

// Insert the new document into the collection
// Note that the `my_attachment` field needs to be declared as an `attachment` data type
peer_a
    .store()
    .execute(
        r#"
        INSERT INTO COLLECTION cars (my_attachment ATTACHMENT)
        DOCUMENTS (:new_document)
    "#,
        Some(
            json!({
                "new_document": new_document,
            })
            .into(),
        ),
    )
    .await?;
```
:::

# Creating MAPs

There are two ways to create a `MAP` structure within a document:

- In an `INSERT` operation — Create a new document and nest it with this set of fields. 

- In an `UPDATE` operation — If the `MAP` does not exist, create it. (See [UPDATE](docId:_5lH6DqAd0itAZoy8_I16))

To represent a highly complex data structure in a `MAP`, consider embedding it with an additional `MAP`. Embedding a `MAP` within a `MAP` establishes an additional hierarchy.&#x20;

The decision to use deeply embedded `MAPS` in a single document or opt for a *flat model* depends on your requirements, relationships between data, and tolerance for certain tradeoffs.&#x20;

:::hint{type="info"}
The flat model is a simple, non‑embedded structure in which you spread your data across multiple, separate documents.&#x20;
:::

## Inserting to Create a MAP

When inserting a new document in Ditto, you can define a field as a `MAP` and include the structure of key-value pairs nested within it — a two-in-one approach. For example:

:::CodeblockTabs
```swift
let arguments: [String: Any] = [
  "newCar": [
    "_id": "123",
    "properties": [
      "color": "blue",
      "mileage": 3000
    ]
  }
];

await ditto.store.execute(
  query: "INSERT INTO COLLECTION cars (properties MAP) DOCUMENTS (:newCar)",
  arguments: arguments);
```

```kotlin
val arguments = mapOf(
  "newCar" to mapOf(
    "_id" to "123",
    "properties" to mapOf(
      "color" to "blue",
      "mileage" to 3000
      )
    )
  )
)

ditto.store.execute("""
  INSERT INTO COLLECTION cars (properties MAP)
  DOCUMENTS (:newCar)
  """,
  arguments)
```

```javascript
const newCar = {
  _id: "123",
  properties: {
    color: 'blue',
    mileage: 3000
  }
}

await ditto.store.execute(`
  INSERT INTO COLLECTION cars (properties MAP)
  DOCUMENTS (:newCar)`,
  { newCar });
```

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

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

DittoQueryResult result = (DittoQueryResult) ditto.store.execute(
    "INSERT INTO COLLECTION cars (properties MAP) 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
            }
        }
    }
);
```

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

var result = await ditto.Store.ExecuteAsync(
  "INSERT INTO COLLECTION cars (properties MAP) DOCUMENTS (:newCar)",
  insertArgs);
```

```cpp
struct Properties {
  std::string color;
  int mileage;
};
struct Car {
  std::string _id;
  Properties properties;
};

// ...

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

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

```rust
struct Args {
  newCar: Car,
}
struct Properties {
  color: String,
  mileage: i32
}
struct Car {
  _id: String,
  properties: Properties
}

// ...

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

await ditto.store().execute(
  "INSERT INTO COLLECTION cars (properties MAP) DOCUMENTS (:newCar)",
  args);
```
:::

Another method to creating a `MAP` within a document is to perform an `UPDATE` operation. &#x20;

In the `UPDATE` approach, you set the structure of key-value pairs and specify the document ID for storage.&#x20;

For example, this statement creates the `MAP` structure — unless it already exists — setting a single key-value pair of color is red within the properties `MAP` for the document with the ID 123 in the cars collection:

:::CodeblockTabs
DQL

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

# Handling Query Execution Results

When writing your insert query, include a completion handler to respond to the result of the query execution.&#x20;

Once defined, you can reuse this handler throughout your codebase, resulting in greater consistency throughout your app. For example:

:::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")),
    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("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
struct Args {
  newCar: Car,
}
struct Car {
  color: String
}

// ...

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

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

