# 保存保存

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

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

插入文档,或用相同的标识符替换文档。重复写入。

Status: document database · free · insert or replace

## 参数 {#parameters}

| Name | Type | Requirement | Description |
| --- | --- | --- | --- |
| `collection` | string | 必填 | 哪个收藏 |
| `data` | JSON text | 必填 | 文档。 带有 `_id` 替换;不插入,插入。 |

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

## 为什么不插入 {#idempotent}

|  | 插入插入 | 保存保存 |
| --- | --- | --- |
| 跑两两下 | 2份文件 | 单文档 |
| 需要先使用 ID | 无 无 | 只替换 |
| 良好 | 事件、日志、 仅附加的 | 具有身份的国家 |

> **这份工作可能要跑两次**
>
> 重试、 重新投送的网钩、 重新导入—— 插入每次尝试都增加一行。 有了节省, 第二次尝试在第一个尝试上降落, 没有任何重复 。

## 取代它携带的田地 {#merge}

您通过的文件设置在已有的文档之上。 您所留下的字段没有被删除, 但您包括的字段已被覆盖, 所以构建您指的整个对象, 而不是一个碎片 。

```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" } }) });
```

- [插入插入](/zh/sdk/ref/connected-storage/run-write/insert): 和小提琴小提琴小提琴
- [更新更新更新](/zh/sdk/ref/connected-storage/run-write/update): 换了冠军
- [run()](/zh/sdk/ref/connected-storage/run): 行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动,行动

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