# $dbSet

`$dbSet` replaces the document completely (or creates it). To change only some fields, use [`$dbUpdate`](/docs/dbupdate/); to change a number safely, use [`$dbIncrement`](/docs/dbincrement/). The data lives in the **server's space** (the user's own space in a direct message). [`$dbSpace`](/docs/dbspace/) switches the rest of the run to the user or the bot. A script can never read another server's or another user's data.

## Syntax

```
$dbSet[collection;id;json;(returnValue)]
```

## Parameters

| Parameter | Description |
|---|---|
| `collection` | Collection name: lowercase letters, digits, `_`, `.` or `-` (up to 64 characters). It is created on first write. |
| `id` | Document id, 1 to 128 bytes. Often a Discord ID. |
| `json` | The document: a JSON object. Keys starting with `$` and `__proto__` are refused. Up to 16 KB (64 KB on a paid plan). |
| `returnValue` | Optional - `yes` to return the result, `no` to return nothing. Absent: a call written on its own prints nothing, a call used as a value (`$var[r;$dbSet[...]]`) returns it. Any other value raises an error. |

## Return value

Used on its own in a script, the function prints nothing, so no revision or JSON leaks into the message. Used as a value of another function, or with `returnValue` set to `yes`, it returns the result below.

- The new revision number of the document. It starts at 1 and goes up at every write.
- Empty on a handled error (see [`$dbLastError`](/docs/dblasterror/)).

## Examples

```bdfd
$dbSet[players;$authorID;{"xp":0,"name":"$username"}]
```

### Build the document with the JSON functions

Writing the JSON by hand breaks as soon as a value contains a `"`. Build it with the JSON functions instead: they escape for you.

```bdfd
$jsonClear
$jsonSet[xp;0]
$jsonSetString[name;$username]
$dbSet[players;$authorID;$jsonStringify]
```

### Where the data goes

The collection is created by its first write, in the current space (the server by default). Put `$dbSpace[user]` or `$dbSpace[bot]` before `$dbSet` to write in the user's or the bot's space instead; see `$dbSpace`.
