---
title: Data Structures and Types
slug: v4-4/data-structures-types
docTags: 
createdAt: 2023-08-02T21:55:32.679Z
---

Ditto provides a flexible and efficient way to store and manage data so you can efficiently sync data for a wide range of use cases.&#x20;

Different data structures in Ditto have distinct behaviors and characteristics that you'll need to be familiar with to achieve your specific goals. &#x20;

This article provides a quick overview of Ditto's [schema-flexible document model](./#schema-flexible-document-objects) and [advanced data types](./#advanced-data-types).&#x20;

:::hint{type="info"}
For an overview of the various operators and path navigations you can use to construct sophisticated queries in your app, see *Platform Manual&#x20;*> [Query Syntax](docId\:MMTiSmYkR3HxZmYS1bi2w).
:::

# Schema-Flexible Document Objects

Ditto stores data in structured JSON-like document objects. Each document consists of sets of human‑readable fields that identify and represent the information the document stores.&#x20;

Each document is nested with a hash-stable tree structure that self-describes the data to be stored and provides the predetermined rules that ensure data consistency and accuracy.&#x20;

In simpler terms, each document in Ditto is essentially a key-value pair, where the key is a name (`string`) and the value can be any supported type in Ditto, which includes `maps`. For more information, see [Fields](./#fields), as follows.

## Supported Types

In Ditto’s document model, the supported data types depend on the CRDTs associated with the document. For more information about CRDTs, see the *Platform Manual&#x20;*> [Data Types](docId\:yxemKH1COm3CSUuMqcnlf) and [Document Model](docId\:AmTy0OpHec33HDf-1IOhZ).

The following snippet provides an example of a basic JSON‑like document object:

```json
{
  "_id" "123abc",
  "name": "Sam",
  "age": 45,
  "isOnline": false
}
```

## Document Size and Sync Performance

Syncing large documents can significantly impact network performance. Instead of storing files exceeding 250kb directly within a document object, carefully consider using `attachments` .&#x20;

:::hint{type="warning"}
Caution is advised when handling large binary data, such as a high‑resolution image or video exceeding 50 megapixels; a deeply embedded document; or a very large document.
:::

For more information, see any of the following:

- *Ditto Basics&#x20;*> [Attachment Objects](./#attachment-objects), as follows.
- *Platform Manual&#x20;*> Document Model:
  - [Complex Structures](docId:8knpxrWcdkFKNW8ZeAIjr)
  - [Evaluation Criteria](docId\:IDUhIsA7KwNFAoWgQWRp9)
  - [Relationships](docId\:LQGzvVHtqzybx_ALD5b8J)
- *Platform Manual&#x20;*> Data Types > [Attachment](docId\:slQOBcNXTyF-KeLi7l8F8)

## Fields

A document consists of sets of fields that self‑describe the data it encodes. Each set signifies a single pair of two associated elements:

- The name identifying the data. (See [Field Property](docId:01CWcZyXG4mgpZ90xn6Oe))
- The value that holds the actual data to store. (See [Field Values](docId:01CWcZyXG4mgpZ90xn6Oe))

Required and randomly generated and assigned by default upon creation, the first set of fields identifies the document. (See [Document Identifiers](./#document-identifiers))

## Document Identifiers

The first set of fields within each document uniquely identifies the data that its document object encodes. When grouped in a collection, this `_id` serves as the primary key identifying the document in the collection.&#x20;

Ditto automatically generates and assigns each new document a unique identifier, or `_id`.

However, if desired, you can pass your own custom `_id` as a parameter in the `upsert` function you use to create a new document. (See [CRUD Fundamentals](docId\:bYukQ4ekkuevjbx_FEuOg))

In addition to having the option to supply your own `_id`, in complex scenarios where you want to create a more intricate and unique identifier for your documents, you can combine two or more distinct elements to form a composite key.&#x20;

For more comprehensive information and how-to instructions, see the *Platform Manual&#x20;*> [CRUD Operations](docId:1CEXFnSWhjeqa_R6yyL-8) > [Upserting and Updating](docId\:L2hFjvzUYyNu5ahZXHwAJ).

## Collection Indexes

If there is a set of documents that contain the same commonly-queried field, such as a string reference to `cars`, you can optimize query speed and reduce peer storage usage by grouping them in an index, or a *collection*.&#x20;

The following snippet and corresponding table provide an example of a string reference to the collection `cars`.

```javascript
const carsCollection = ditto.store.collection('cars')
```

To help better understand, think of a collection like a SQL database *table* and the documents it holds like table *rows*: 

::Image[]{src="https://api.archbee.com/api/optimize/qoRkNxW5fJ81r_NqVpc8C/l5wQm0LFLAZUOYMVnozv0_tableexample.png" size="46" width="828" height="626" position="flex-start" showCaption="false"}

## Attachment Objects

To improve performance, instead of storing a file that encodes large amounts of binary data as a document, you can opt to store it as a separate, explicitly fetched object known as an `attachment`.

With the `attachment` CRDT, you can sync between peers without querying and merging.&#x20;

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. For instance, in the [iOS demo chat app](https://github.com/getditto/demoapp-chat/tree/main/iOS), you can see a savvy implementation of `ATTACHMENT` with a full-resolution avatar image from a collection named `User`.

For more comprehensive information and how-to instructions, see the *Platform Manual&#x20;*> Data Types > [Attachment](docId\:yxemKH1COm3CSUuMqcnlf).

## Relationship Models

There are several methods for linking related data items and organizing them for easy lookup:

- Embedded JSON object that acts as a `REGISTER` type
- Embedded `MAP`
- Field referencing another document

All three approaches use a foreign-key relationship to establish a structure resembling a parent-child hierarchy. In this hierarchy, the key functions as the parent, and its encapsulated values, represented as a set of key-value pairs, serve as children.

The choice between a `MAP` and an embedded JSON object that functions as a `REGISTER` depends on your app's usage patterns and the specific conflict resolution requirements in your data model.&#x20;

The following table provides a complete overview of the relationships you can establish in Ditto:&#x20;

| **Relationship** | **Description**                                                                                                                                                      | **Approaches**                                                                                                  |
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| One-to-many      | Associates a parent element with children elements to establish a hierarchy.                                                                                         | - Embed a `map`
- Reference a field to a document&#x20;
- Reference a document to a collection&#x20;            |
| Many-to-many     | Associates multiple entities in one collection with multiple entities in another collection.                                                                         | * Embed a `map`&#x20;
* List items in an `array`
* Create references between documents in different collections |
| Many-to-one      | Associates two or more collections, where one collection refers to the primary key of another collection to create a meaningful relationship between the datasets.   | - Embed a `map`
- Create references between documents in different collections                                  |

For more information, see *Ditto Basics* > [CRUD Fundamentals](docId\:bYukQ4ekkuevjbx_FEuOg) and *Platform Manual&#x20;*> [CRUD Operations](docId:1CEXFnSWhjeqa_R6yyL-8).

# Advanced Data Types

As a semi-structured distributed database, Ditto leverages conflict‑free replicated data types (*CRDT*) technology to enable advanced data exchange capabilities. 

To get the most out of Ditto, you'll need to work with one or more CRDTs. The`register` type is the most common and simple type to use. 

For more information, see *Platform Manual&#x20;*>  [Register](docId\:yxemKH1COm3CSUuMqcnlf).

## Overview

The following table provides a quick overview of the advanced data types you can use in Ditto, along with their guiding principles for conflict resolution, or *merge semantics*, a brief description, and a common usage scenario:

:::hint{type="info"}
In Ditto’s document model, the supported primitive data types depend on the CRDTs associated with the document. For an overview of the data types that each CRDT allows, see *Platform Manual&#x20;*> [Data Types](docId\:yxemKH1COm3CSUuMqcnlf).
:::

| **Type**     | **Merge Semantics**                                                                                | **Description**                                                                                                                                                   | **Use Case**                                                                  |
| ------------ | -------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| `register`   | Last‑Write‑Wins Register, <br />Delta-state replication                                            | Stores a single value and allows for concurrent updates.                                                                                                          | Updates associated with later temporal timestamps *always* win.               |
| `map`        | Add-Wins Map,<br />Delta-state replication                                                         | Working in conjunction with the Register, stores the mapping of temporal timestamps to the values written in the Register to help resolve concurrency conflicts.  | Make a list of items in a document and update those items over time.          |
| `counter`    | Positive or Negative Counter,<br />The sum of all `Site_ID` Counters,<br />Delta-state replication | Converts a number value for a given key into a Counter. <br />Unlike a primitive `number`, value increments and decrements merge without conflict.                | Manage inventory and handle votes, such as stock details and survey results.  |
| `attachment` | Last-Write‑Wins Register,<br />Merges only when explicitly fetched                                 | Stores very large amounts of binary data, such as an image file, and allows for concurrent updates.                                                               | Reduce Small Peer resource usage by storing data outside of memory.           |
| `array`      | Last‑Write‑Wins Register,<br />Delta-state replication                                             | An extension of the `register` type,                                                                                                                              |                                                                               |



