# update

The .update() method for the SurrealDB Rust SDK updates all or specific records in the database.

**3.x**

Update all or specific records in the database.

```rust title="Method Syntax"
db.update(resource)
```

The `.update()` method is followed by second method that refers to the type of update to use: an update with `.content()`, `.merge()`, or `.patch()`.

## `.update().content()`

Updates all records in a table, or a specific record, in the database.

```rust title="Method Syntax"
db.update(resource).content(data)
```

> [!NOTE]
> This function replaces the current document / record data with the specified data.

### Arguments
<table>
    <thead>
        <tr>
            <th colspan="2" scope="col">Argument</th>
            <th colspan="2" scope="col">Type</th>
            <th colspan="2" scope="col">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Argument">
                <code>resource</code>
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The table name or the specific record ID to create.
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="row" data-label="Argument">
                <code>data</code>
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The document / record data to insert.
            </td>
        </tr>
    </tbody>
</table>

### Example usage

```rust
use surrealdb::Surreal;
use surrealdb::engine::remote::ws::Ws;
use surrealdb::opt::auth::Root;
use surrealdb::types::SurrealValue;

#[derive(Debug, SurrealValue, Default)]
struct Person {
    name: Option<String>,
    company: Option<String>,
    settings: Option<Settings>,
}

#[derive(Debug, SurrealValue)]
struct Settings {
    active: bool,
    marketing: bool,
}

#[derive(Debug, SurrealValue)]
struct Company {
    company: String,
}

#[tokio::main]
async fn main() -> surrealdb::Result<()> {
    let db = Surreal::new::<Ws>("127.0.0.1:8000").await?;

    db.signin(Root {
        username: "root".to_string(),
        password: "secret".to_string(),
    })
    .await?;

    db.use_ns("main").use_db("main").await?;

    db.query("CREATE person:tobie, person:jaime").await?;

    // Update all records in a table
    let people: Vec<Person> = db
        .update("person")
        .content(Company {
            company: "SurrealDB".into(),
        })
        .await?;
    dbg!(people);
    Ok(())
}
```

### Translated query
This function will run the following query in the database:

```surql
UPDATE $resource CONTENT $data;
```

### Restrict records with `.range()`

Table-scoped updates accept [`.range(...)`](https://docs.rs/surrealdb/latest/surrealdb/method/struct.Update.html#method.range-1) before `.content`, `.merge`, or `.patch`, limiting which record IDs are affected:

```rust
use surrealdb::{
    engine::any::connect,
    opt::Resource,
    types::{SurrealValue, ToSql, Value},
};

#[derive(SurrealValue)]
struct Content {
    second_half_of_alphabet: bool,
}

#[tokio::main]
async fn main() {
    let db = connect("memory").await.unwrap();
    db.use_ns("ns").use_db("db").await.unwrap();

    db.query("CREATE person:alucard, person:plato, person:vlad")
        .await
        .unwrap();

    let res = db
        .update::<Value>(Resource::from("person"))
        .range("n"..="z")
        .content(Content {
            second_half_of_alphabet: true,
        })
        .await
        .unwrap()
        .to_sql();
    println!("{res:?}");
}
```

## `.update().merge()`

Modifies all records in a table, or a specific record, in the database.

```rust title="Method Syntax"
db.update(resource).merge(data)
```

> [!NOTE]
> This function merges the current document / record data with the specified data.

### Arguments
<table>
    <thead>
        <tr>
            <th colspan="2" scope="col">Argument</th>
            <th colspan="2" scope="col">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Argument">
                <code>resource</code>
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The table name or the specific record ID to create.
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="row" data-label="Argument">
                <code>data</code>
            </td>
            <td colspan="2" scope="row" data-label="Type">
                <code>resource</code>
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The document / record data to insert.
            </td>
        </tr>
    </tbody>
</table>

### Example usage

```rust
use surrealdb::Surreal;
use surrealdb::engine::remote::ws::Ws;
use surrealdb::opt::auth::Root;
use surrealdb::types::SurrealValue;

#[derive(Debug, SurrealValue, Default)]
struct Person {
    name: String,
    company: Option<String>,
    active: Option<bool>,
    marketing: Option<bool>,
}

#[derive(Debug, SurrealValue)]
struct Settings {
    active: bool,
    marketing: bool,
}

#[derive(Debug, SurrealValue)]
struct Company {
    company: String,
}

#[tokio::main]
async fn main() -> surrealdb::Result<()> {
    let db = Surreal::new::<Ws>("127.0.0.1:8000").await?;

    db.signin(Root {
        username: "root".to_string(),
        password: "secret".to_string(),
    })
    .await?;

    db.use_ns("ns").use_db("db").await?;

    db.query("CREATE person:tobie SET name = 'Tobie'; CREATE person:jaime SET name = 'jaime';")
        .await?;

    // Update all records in a table
    let people: Vec<Person> = db
        .update("person")
        .merge(Company {
            company: "SurrealDB".into(),
        })
        .await?;
    dbg!(people);

    // Update a single record
    let person: Option<Person> = db
        .update(("person", "jaime"))
        .merge(Settings {
            active: true,
            marketing: true,
        })
        .await?;
    dbg!(person);
    Ok(())
}
```

### Translated query
This function will run the following query in the database:

```surql
UPDATE $resource MERGE $data;
```

## `.update().patch()`

Applies JSON Patch changes to all records, or a specific record, in the database.

```rust title="Method Syntax"
db.update(resource).patch(patch_op)
```

> [!NOTE]
> This function patches the current document / record data with the specified JSON Patch data.

### Arguments
<table>
    <thead>
        <tr>
            <th colspan="2" scope="col">Argument</th>
            <th colspan="2" scope="col">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Argument">
                <code>resource</code>
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The table name or the specific record ID to modify.
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="row" data-label="Argument">
                <code>data</code>
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The JSON Patch data with which to modify the records.
            </td>
        </tr>
    </tbody>
</table>

### Example usage

The `.patch()` method uses a struct called a `PatchOp` that contains the four methods `add()`, `change()`, `remove()`, and `replace()`. Each of these methods takes different arguments depending on the operation. For example, `PathOp::remove()` only takes a single argument (a path), while `PathOp::replace()` takes a second value for the replacement value.

```rust
use surrealdb::Surreal;
use surrealdb::engine::remote::ws::Ws;
use surrealdb::opt::PatchOp;
use surrealdb::opt::auth::Root;
use surrealdb::types::{Datetime, SurrealValue};

#[derive(Debug, SurrealValue, Default)]
struct Person {
    name: String,
    company: Option<String>,
    settings: Option<Settings>,
    created_at: Option<Datetime>,
    tags: Option<Vec<String>>,
}

#[derive(Debug, SurrealValue)]
struct Settings {
    active: bool,
}

#[tokio::main]
async fn main() -> surrealdb::Result<()> {
    let db = Surreal::new::<Ws>("127.0.0.1:8000").await?;

    db.signin(Root {
        username: "root".to_string(),
        password: "secret".to_string(),
    })
    .await?;

    db.use_ns("main").use_db("main").await?;

    db.query(
        "
        CREATE person:tobie SET name = 'Tobie', company = 'SurrealDB'; 
        CREATE person:jaime SET name = 'jaime', company = 'SurrealDB';",
    )
    .await?;

    // Update all records in a table
    let people: Vec<Person> = db
        .update("person")
        .patch(PatchOp::replace("/created_at", Datetime::default()))
        .await?;
    dbg!(people);

    // Update a record with a specific ID
    let person: Option<Person> = db
        .update(("person", "tobie"))
        .patch(PatchOp::replace("/settings/active", false))
        .patch(PatchOp::add("/tags", ["developer", "engineer"]))
        .patch(PatchOp::remove("/company"))
        .await?;
    dbg!(person);
    Ok(())
}
```

#### Multiple operations with `PatchOps`

Chaining `.patch()` once per operation works, but each call adds a level of nesting to the builder. [`PatchOps`](https://docs.rs/surrealdb/latest/surrealdb/opt/struct.PatchOps.html) collects the operations into a single value instead, and carries the same four methods so that they can be chained on one another.

```rust
use surrealdb::engine::any::connect;
use surrealdb::opt::PatchOps;
use surrealdb::types::{Datetime, SurrealValue};

#[derive(Debug, SurrealValue, Default)]
struct Person {
    name: String,
    company: Option<String>,
    settings: Option<Settings>,
    created_at: Option<Datetime>,
    tags: Option<Vec<String>>,
}

#[derive(Debug, SurrealValue)]
struct Settings {
    active: bool,
}

#[tokio::main]
async fn main() -> surrealdb::Result<()> {
    let db = connect("memory").await?;
    db.use_ns("main").use_db("main").await?;

    db.query(
        "CREATE person:tobie SET name = 'Tobie', company = 'SurrealDB', settings = { active: true }",
    )
    .await?
    .check()?;

    let person: Option<Person> = db
        .update(("person", "tobie"))
        .patch(
            PatchOps::new()
                .replace("/settings/active", false)
                .add("/tags", ["developer", "engineer"])
                .remove("/company"),
        )
        .await?;
    dbg!(person);
    Ok(())
}
```

`PatchOps` is built up in order and applied in order, so an operation can depend on one before it. A single `PatchOp` still works wherever `PatchOps` is expected, as `.patch()` takes anything that converts into `PatchOps`, including a `Vec<PatchOp>`.

> [!NOTE]
> Removing a field the target struct declares as non-optional will make the response fail to deserialise. Take the result as a `Value`, or declare the field as an `Option`, when a patch removes it.

### Translated query
This function will run the following query in the database:

```surql
UPDATE $resource PATCH $data;
```

### See also

* [.update() method on Docs.rs](https://docs.rs/surrealdb/latest/surrealdb/struct.Surreal.html#method.update)

**2.x**

Update all or specific records in the database.

```rust title="Method Syntax"
db.update(resource)
```

The `.update()` method is followed by second method that refers to the type of update to use: an update with `.content()`, `.merge()`, or `.patch()`.

## `.update().content()`

Updates all records in a table, or a specific record, in the database.

```rust title="Method Syntax"
db.update(resource).content(data)
```

> [!NOTE]
> This function replaces the current document / record data with the specified data.

### Arguments
<table>
    <thead>
        <tr>
            <th colspan="2" scope="col">Argument</th>
            <th colspan="2" scope="col">Type</th>
            <th colspan="2" scope="col">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Argument">
                <code>resource</code>
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The table name or the specific record ID to create.
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="row" data-label="Argument">
                <code>data</code>
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The document / record data to insert.
            </td>
        </tr>
    </tbody>
</table>

### Example usage

```rust
use serde::{Deserialize, Serialize};
use surrealdb::engine::remote::ws::Ws;
use surrealdb::opt::auth::Root;
use surrealdb::Surreal;

#[derive(Debug, Serialize, Deserialize, Default)]
struct Person {
    name: Option<String>,
    company: Option<String>,
    settings: Option<Settings>,
}

#[derive(Debug, Serialize, Deserialize)]
struct Settings {
    active: bool,
    marketing: bool,
}

#[derive(Debug, Serialize)]
struct Company {
    company: String,
}

#[tokio::main]
async fn main() -> surrealdb::Result<()> {
    let db = Surreal::new::<Ws>("127.0.0.1:8000").await?;

    db.signin(Root {
        username: "root",
        password: "secret",
    })
    .await?;

    db.use_ns("ns").use_db("db").await?;

    db.query("CREATE person:tobie, person:jaime").await?;

    // Update all records in a table
    let people: Vec<Person> = db
        .update("person")
        .content(Company {
            company: "SurrealDB".into(),
        })
        .await?;
    dbg!(people);
    Ok(())
}
```

### Translated query
This function will run the following query in the database:

```surql
UPDATE $resource CONTENT $data;
```

## `.update().merge()`

Modifies all records in a table, or a specific record, in the database.

```rust title="Method Syntax"
db.update(resource).merge(data)
```

> [!NOTE]
> This function merges the current document / record data with the specified data.

### Arguments
<table>
    <thead>
        <tr>
            <th colspan="2" scope="col">Argument</th>
            <th colspan="2" scope="col">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Argument">
                <code>resource</code>
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The table name or the specific record ID to create.
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="row" data-label="Argument">
                <code>data</code>
            </td>
            <td colspan="2" scope="row" data-label="Type">
                <code>resource</code>
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The document / record data to insert.
            </td>
        </tr>
    </tbody>
</table>

### Example usage
```rust
use serde::{Deserialize, Serialize};
use surrealdb::engine::remote::ws::Ws;
use surrealdb::opt::auth::Root;
use surrealdb::Surreal;

#[derive(Debug, Serialize, Deserialize, Default)]
struct Person {
    name: String,
    company: Option<String>,
    active: Option<bool>,
    marketing: Option<bool>,
}

#[derive(Debug, Serialize, Deserialize)]
struct Settings {
    active: bool,
    marketing: bool,
}

#[derive(Debug, Serialize)]
struct Company {
    company: String,
}

#[tokio::main]
async fn main() -> surrealdb::Result<()> {
    let db = Surreal::new::<Ws>("127.0.0.1:8000").await?;

    db.signin(Root {
        username: "root",
        password: "secret",
    })
    .await?;

    db.use_ns("ns").use_db("db").await?;

    db.query("CREATE person:tobie SET name = 'Tobie'; CREATE person:jaime SET name = 'jaime';")
        .await?;

    // Update all records in a table
    let people: Vec<Person> = db
        .update("person")
        .merge(Company {
            company: "SurrealDB".into(),
        })
        .await?;
    dbg!(people);

    // Update a single record
    let person: Option<Person> = db
        .update(("person", "jaime"))
        .merge(Settings {
            active: true,
            marketing: true,
        })
        .await?;
    dbg!(person);
    Ok(())
}
```

### Translated query
This function will run the following query in the database:

```surql
UPDATE $resource MERGE $data;
```

## `.update().patch()`

Applies JSON Patch changes to all records, or a specific record, in the database.

```rust title="Method Syntax"
db.update(resource).patch(patch_op)
```

> [!NOTE]
> This function patches the current document / record data with the specified JSON Patch data.

### Arguments
<table>
    <thead>
        <tr>
            <th colspan="2" scope="col">Argument</th>
            <th colspan="2" scope="col">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Argument">
                <code>resource</code>
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The table name or the specific record ID to modify.
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="row" data-label="Argument">
                <code>data</code>
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The JSON Patch data with which to modify the records.
            </td>
        </tr>
    </tbody>
</table>

### Example usage

The `.patch()` method uses a struct called a `PatchOp` that contains the four methods `add()`, `change()`, `remove()`, and `replace()`. Each of these methods takes different arguments depending on the operation. For example, `PathOp::remove()` only takes a single argument (a path), while `PathOp::replace()` takes a second value for the replacement value.

```rust
use serde::{Deserialize, Serialize};
use surrealdb::engine::remote::ws::Ws;
use surrealdb::opt::auth::Root;
use surrealdb::opt::PatchOp;
use surrealdb::sql::Datetime;
use surrealdb::Surreal;

#[derive(Debug, Serialize, Deserialize, Default)]
struct Person {
    name: String,
    company: Option<String>,
    settings: Option<Settings>,
    created_at: Option<Datetime>,
    tags: Option<Vec<String>>,
}

#[derive(Debug, Serialize, Deserialize)]
struct Settings {
    active: bool,
}

#[tokio::main]
async fn main() -> surrealdb::Result<()> {
    let db = Surreal::new::<Ws>("127.0.0.1:8000").await?;

    db.signin(Root {
        username: "root",
        password: "secret",
    })
    .await?;

    db.use_ns("ns").use_db("db").await?;

    db.query(
        "
        CREATE person:tobie SET name = 'Tobie', company = 'SurrealDB'; 
        CREATE person:jaime SET name = 'jaime', company = 'SurrealDB';",
    )
    .await?;

    // Update all records in a table
    let people: Vec<Person> = db
        .update("person")
        .patch(PatchOp::replace("/created_at", Datetime::default()))
        .await?;
    dbg!(people);

    // Update a record with a specific ID
    let person: Option<Person> = db
        .update(("person", "tobie"))
        .patch(PatchOp::replace("/settings/active", false))
        .patch(PatchOp::add("/tags", &["developer", "engineer"]))
        .patch(PatchOp::remove("/company"))
        .await?;
    dbg!(person);
    Ok(())
}
```

### Translated query
This function will run the following query in the database:

```surql
UPDATE $resource PATCH $data;
```

### See also

* [.update() method on Docs.rs](https://docs.rs/surrealdb/latest/surrealdb/struct.Surreal.html#method.update)
