# save

Canonical URL: https://developers.iagenify.com/sdk/ref/connected-storage/run-write/save/
Language: en

`storage.run({ action: "save", collection, data })`

Inserts a document, or replaces the one with the same identifier. The repeatable write.

Status: document database · free · insert or replace

## Parameters {#parameters}

| Name | Type | Requirement | Description |
| --- | --- | --- | --- |
| `collection` | string | required | Which collection. |
| `data` | JSON text | required | The document. With an `_id` it replaces; without, it inserts. |

```javascript
// No _id: inserted
await storage.run({ action: "save", collection: "profiles",
  data: JSON.stringify({ email: "a@example.com", plan: "go" }) });
// { ok: true, id: "66f0…" }

// With _id: replaced, or created if it is not there
await storage.run({ action: "save", collection: "profiles",
  data: JSON.stringify({ _id: "66f0…", email: "a@example.com", plan: "starter" }) });
// { ok: true, id: "66f0…", modifiedCount: 1 }
```

## Why this rather than insert {#idempotent}

|  | insert | save |
| --- | --- | --- |
| Run twice | two documents | one document |
| Needs the id first | no | only to replace |
| Good for | events, logs, anything append-only | state that has an identity |

> **This is the one to reach for in a job that might run twice**
>
> A retry, a redelivered webhook, a resumed import — with insert each attempt adds a row. With save, the second attempt lands on the first and nothing is duplicated.

## It replaces the fields it carries {#merge}

The document you pass is set over the existing one. Fields you leave out are not removed, but fields you include are overwritten — so build the whole object you mean, rather than a fragment.

```javascript
// To change one field and leave the rest alone, update is the clearer tool
await storage.run({ action: "update", collection: "profiles",
  filter: JSON.stringify({ _id: id }),
  update: JSON.stringify({ $set: { plan: "starter" } }) });
```

- [insert](/sdk/ref/connected-storage/run-write/insert): Quand chaque appel doit ajouter.
- [update](/sdk/ref/connected-storage/run-write/update): Quand un seul champ change.
- [run()](/sdk/ref/connected-storage/run): Toutes les actions, les garde-fous et ce que chacune coûte.

```python
import json

# No _id: inserted
storage.run(action="save", collection="profiles",
            data=json.dumps({"email": "a@example.com", "plan": "go"}))
# {"ok": True, "id": "66f0…"}

# With _id: replaced, or created if it is not there
storage.run(action="save", collection="profiles",
            data=json.dumps({"_id": "66f0…", "email": "a@example.com", "plan": "starter"}))
# {"ok": True, "id": "66f0…", "modifiedCount": 1}
```

```python
import json

# To change one field and leave the rest alone, update is the clearer tool
storage.run(action="update", collection="profiles",
            filter=json.dumps({"_id": profile_id}),
            update=json.dumps({"$set": {"plan": "starter"}}))
```
