> For the complete documentation index, see [llms.txt](https://docs.adiom.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.adiom.io/enterprise/running-dsynct/data-transformations/templates.md).

# Templates

Copy the config closest to your case and adjust the namespaces and field names. Each config on this page was run through [Transform Studio](https://docs.adiom.io/enterprise/running-dsynct/web-api.md#transform-studio); the sample input and output are shown so that you can reproduce the result.

Recipes can be combined in one mapping. Remember that a path can have only one `cel` entry.

* [Starting points by source and destination](#starting-points)
* [Field recipes](#field-recipes)
* [Document recipes](#document-recipes)
* [Reverse sync pairs](#reverse-sync-pairs)

## Starting Points

### Cosmos DB NoSQL to MongoDB

See [Cosmos DB NoSQL to MongoDB](https://docs.adiom.io/enterprise/running-dsynct/cosmos-db-nosql-to-mongo.md#data-type-and-id-considerations) for the two ID templates (shard key `/id`, and a separate shard key).

### SQL Batch to MongoDB

The SQL Batch source emits flat JSON rows and does not add an `id` field. Declare the key columns with `idkeys` and build `_id` from them.

```yaml
mappings:
  - namespace: dbo.orders
    mapnamespace: shop.orders
    idkeys: ["order_id"]
    delete: ["order_id"]
    add: ["_id"]
    mapid: int(id)
    cel:
      _id: int(id)
      created_at: timestamp(self)
      total: bson_decimal128(string(self))
      qty: int(self)
    map:
      qty: int32
```

|                      |                                                                                                                                                  |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| Input (JSON)         | `{"order_id": 7, "customer_id": 3, "total": 19.99, "qty": 2, "created_at": "2024-01-02T03:04:05Z"}`                                              |
| Output (BSON)        | `{"_id": NumberLong(7), "customer_id": NumberLong(3), "total": NumberDecimal("19.99"), "qty": 2, "created_at": ISODate("2024-01-02T03:04:05Z")}` |
| Update and delete ID | `_id` = `NumberLong(7)`                                                                                                                          |

For a string key, use `id` in place of `int(id)`. For a key with several columns, see the [multi-part ID examples](https://docs.adiom.io/enterprise/running-dsynct/data-transformations/data-types.md#multi-part-id-examples).

### MongoDB to Cosmos DB NoSQL

ObjectIDs, dates and Decimal128 values in regular fields are converted to strings automatically. Only the ID needs a mapping.

```yaml
mappings:
  - namespace: shop.orders
    delete: ["_id"]
    add: ["id"]
    mapid: bson_object_id_string(id)
    cel:
      id: bson_object_id_string(id)
```

|                      |                                                                                                                                                                                      |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Input (BSON)         | `{"_id": ObjectId("65f000000000000000000001"), "customer_id": ObjectId("65f000000000000000000002"), "total": NumberDecimal("19.99"), "created_at": ISODate("2024-01-02T03:04:05Z")}` |
| Output (JSON)        | `{"id": "65f000000000000000000001", "customer_id": "65f000000000000000000002", "total": "19.99", "created_at": "2024-01-02T03:04:05Z"}`                                              |
| Update and delete ID | `id` = `"65f000000000000000000001"`                                                                                                                                                  |

This template fits a container whose shard key is `/id`. With any other shard key, the destination ID also needs the shard key value, and it must be computable from the MongoDB `_id` alone. See [What Transforms Cannot Do](https://docs.adiom.io/enterprise/running-dsynct/data-transformations.md#what-transforms-cannot-do).

### One Mapping for Every Namespace

Use `defaultmapping` when the same rule applies to all namespaces, and `namespacemapper` to rename them with an expression.

```yaml
namespacemapper: '"archive." + self.split(".")[1]'
defaultmapping: default
mappings:
  - namespace: default
    delete: ["__v"]
```

A document from `shop.users` is written to `archive.users` without its `__v` field.

## Field Recipes

### Rename a Field

```yaml
mappings:
  - namespace: shop.users
    delete: ["fullname"]
    add: ["name"]
    cel:
      name: parent.fullname
```

`{"_id": 1, "fullname": "Ann Lee", "age": 3}` becomes `{"_id": 1, "name": "Ann Lee", "age": 3}`.

### Change Nested Fields and Array Elements

A path that goes through an array applies to every element.

```yaml
mappings:
  - namespace: shop.users
    delete: ["address.internal_code", "orders.debug"]
    cel:
      address.city: self.upperAscii()
      orders.total: double(self)
```

|        |                                                                                                                                         |
| ------ | --------------------------------------------------------------------------------------------------------------------------------------- |
| Input  | `{"_id": 1, "address": {"city": "oslo", "internal_code": "x"}, "orders": [{"total": "12.50", "debug": 1}, {"total": "3", "debug": 2}]}` |
| Output | `{"_id": 1, "address": {"city": "OSLO"}, "orders": [{"total": 12.5}, {"total": 3.0}]}`                                                  |

### Convert Types (JSON to BSON)

Use `cel` for the conversion and add `map` where CEL has no matching type (32-bit integers, ObjectIDs).

```yaml
mappings:
  - namespace: shop.orders
    cel:
      created_at: timestamp(self)
      price: bson_decimal128(self)
      customer_id: self
      qty: int(self)
    map:
      customer_id: bson_object_id
      qty: int32
```

| Field         | Input                        | Output         |
| ------------- | ---------------------------- | -------------- |
| `created_at`  | `"2024-01-02T03:04:05Z"`     | BSON date      |
| `price`       | `"19.99"`                    | Decimal128     |
| `customer_id` | `"65f000000000000000000001"` | ObjectID       |
| `qty`         | `"3"`                        | 32-bit integer |

This config converts fields only. Add the ID mapping from a [starting point](#starting-points).

### Handle a Field With Mixed Types

`int()` and `string()` accept several input types, so one expression can normalize a field that holds strings in some documents and numbers in others.

```yaml
mappings:
  - namespace: shop.users
    cel:
      age: int(self)
      zip: string(self)
```

`{"age": "42", "zip": 12345}` and `{"age": 42.0, "zip": "0123"}` both come out with an integer `age` and a string `zip`.

### Add Constant and Computed Fields

```yaml
env:
  source_system: legacy-crm
mappings:
  - namespace: shop.users
    add: ["migrated_from", "migrated_at"]
    cel:
      migrated_from: env.source_system
      migrated_at: timestamp(now_millis() / 1000)
```

Every document gets `migrated_from: "legacy-crm"` and a `migrated_at` date. `migrated_at` is set again each time the document is updated through CDC.

### Add or Remove a Field Conditionally

Return `optional.none()` to leave a field out.

```yaml
mappings:
  - namespace: shop.users
    add: ["email_domain"]
    cel:
      email_domain: 'has(doc.email) ? optional.of(doc.email.split("@")[1]) : optional.none()'
      nickname: 'self == "" ? optional.none() : optional.of(self)'
```

| Input                                           | Output                                                  |
| ----------------------------------------------- | ------------------------------------------------------- |
| `{"_id": 1, "email": "a@x.io", "nickname": ""}` | `{"_id": 1, "email": "a@x.io", "email_domain": "x.io"}` |
| `{"_id": 2, "nickname": "z"}`                   | `{"_id": 2, "nickname": "z"}`                           |

### Anonymize Fields

The `fake_*` functions return the same output for the same seed, so seeding with the ID keeps a document's fake values stable across initial sync and CDC.

```yaml
mappings:
  - namespace: shop.users
    cel:
      name: fake_name(id)
      email: fake_email(id)
      phone: fake_phone(id)
      ssn: base64.encode(sha256(self))
```

`{"_id": "u1", "name": "Ann", "email": "a@x.io", "phone": "1", "ssn": "123"}` becomes `{"_id": "u1", "name": "Walter Walker", "email": "feeney.rosa@yahoo.com", "phone": "(206) 426-2014", "ssn": "pmWkWSBCL51Bfkhn79xPuKBKHz//H6B+mY6G9/eieuM="}`.

## Document Recipes

### Skip Documents by ID

`filter` keeps a document when the expression is true. It only sees the ID, and it applies to initial sync, updates and deletes alike.

```yaml
mappings:
  - namespace: shop.events
    filter: '!string(id).startsWith("test-")'
```

### Skip Documents by Content

```yaml
mappings:
  - namespace: shop.users
    self: 'has(doc.archived) && doc.archived ? optional.none() : optional.of(self)'
```

Documents with `archived: true` are not written. A later delete for such a document is still sent to the destination, where it matches nothing. If a document is written and later becomes archived, the copy on the destination is not removed.

### Copy a Namespace to Two Destinations

Two mappings with the same `namespace` both run. Give each a different `mapnamespace`.

```yaml
mappings:
  - namespace: shop.users
    mapnamespace: app.users
    delete: ["audit"]
  - namespace: shop.users
    mapnamespace: audit.users
    delete: ["name", "email"]
```

`{"_id": 1, "name": "a", "email": "a@x.io", "audit": {"by": "x"}}` is written to `app.users` as `{"_id": 1, "name": "a", "email": "a@x.io"}` and to `audit.users` as `{"_id": 1, "audit": {"by": "x"}}`. Updates and deletes go to both.

## Reverse Sync Pairs

A reverse sync is a second sync with source and destination swapped and its own transform file. The reverse file undoes the ID and type mappings of the forward file. See [Reverse Sync](https://docs.adiom.io/enterprise/running-dsynct/data-transformations/designing-and-testing.md#reverse-sync).

Forward, SQL Batch to MongoDB, is the [template above](#sql-batch-to-mongodb). Its reverse, from MongoDB back to JSON rows:

```yaml
mappings:
  - namespace: shop.orders
    mapnamespace: dbo.orders
    finalidkeys: ["order_id"]
    delete: ["_id"]
    add: ["order_id"]
    mapid: id
    cel:
      order_id: id
```

|               |                                                                                                                                                  |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| Input (BSON)  | `{"_id": NumberLong(7), "customer_id": NumberLong(3), "total": NumberDecimal("19.99"), "qty": 2, "created_at": ISODate("2024-01-02T03:04:05Z")}` |
| Output (JSON) | `{"order_id": 7, "customer_id": 3, "total": "19.99", "qty": 2, "created_at": "2024-01-02T03:04:05Z"}`                                            |

Note that `total` comes back as a string, not a number. A round trip does not always restore the original type; check each converted field.

For ID pairs between JSON and BSON (rename, ObjectID, multi-part), the [JSON to BSON](https://docs.adiom.io/enterprise/running-dsynct/data-transformations/data-types.md#json-to-bson-examples) and [BSON to JSON](https://docs.adiom.io/enterprise/running-dsynct/data-transformations/data-types.md#bson-to-json-examples) examples are written as forward and reverse pairs.
