---
title: "Single Document Patch Operations"
url: "https://docs.ravendb.net/6.2/client-api/operations/patching/single-document"
version: "6.2"
language: "java"
---

# Single Document Patch Operations

> Client language: Java. Also available for [C#](https://docs.ravendb.net/6.2/client-api/operations/patching/single-document.md), [Node.js](https://docs.ravendb.net/6.2/client-api/operations/patching/single-document.nodejs.md).
>
> RavenDB publishes an official agent skill for coding assistants at https://docs.ravendb.net/skills/ravendb/SKILL.md (also installable with `npx skills add ravendb/skills`). The skill describes itself as: "Read this before writing any RavenDB query, client call or /databases/ request. Covers server setup, document modelling, the Node.js, .NET and Python clients, RQL, indexes, vector search and AI agents. Code written from recall tends to run and return the wrong rows, because RQL resembles SQL and the clients take field names as plain strings."

> **Note**
>
> The **Patch** operation is used to perform partial document updates without having to load, modify, and save a full document.  
> The whole operation is executed on the server side and is useful as a performance enhancement or for updating denormalized data in entities.
>
> The current page deals with patch operations on single documents.
>
> Patching has three possible interfaces: [Session API](#session-api), [Session API using defer](#session-api-using-defer), and [Operations API](#operations-api).
>
> Patching can be done from the client as well as in the studio.
>
> In this page:  
> [API overview](#api-overview)  
> [Examples](#examples)

## API overview

## Session API

A session interface that allows performing the most common patch operations.  
The patch request will be sent to server only when calling `saveChanges`, this way it's possible to perform multiple operations in one request to the server.

### Increment Field Value

`session.advanced().increment`

```java
<T, U> void increment(String id, String path, U valueToAdd);

<T, U> void increment(T entity, String path, U valueToAdd);
```

| Parameters | | |
| - | - | - |
| **T** | `Class` | Entity class |
| **U** | `Class` | Field class, must be of numeric type, or a `String` of `char` for string concatenation |
| **entity** | `T` | Entity on which the operation should be performed. The entity should be one that was returned by the current session in a `load` or `query` operation, this way, the session can track down the entity's ID |
| **entity id** | `String` | Entity ID on which the operation should be performed. |
| **delta** | `U` | Value to be added. |

- Note how numbers are handled with the [JavaScript engine](https://docs.ravendb.net/6.2/server/kb/numbers-in-ravendb.md) in RavenDB.

### Set Field Value

`session.advanced().patch`

```java
<T, U> void patch(String id, String path, U value);

<T, U> void patch(T entity, String path, U value);
```

| Parameters | | |
| - | - | - |
| **T** | `Class` | Entity Class |
| **U** | `Class` | Field class |
| **entity** | `T` | Entity on which the operation should be performed. The entity should be one that was returned by the current session in a `load` or `query` operation, this way, the session can track down the entity's ID |
| **entity id** | `String` | Entity ID on which the operation should be performed. |
| **delta** | `U` | Value to set. |

### Array Manipulation

`session.advanced().patch`

```java
<T, U> void patch(T entity, String pathToArray, Consumer<JavaScriptArray<U>> arrayAdder);

<T, U> void patch(String id, String pathToArray, Consumer<JavaScriptArray<U>> arrayAdder);
```

| Parameters | | |
| - | - | - |
| **T** | `Class` | Entity class |
| **U** | `Class` | Field class |
| **entity** | `T` | Entity on which the operation should be performed. The entity should be one that was returned by the current session in a `Load` or `Query` operation, this way, the session can track down the entity's ID |
| **entity id** | `String` | Entity ID on which the operation should be performed. |
| **arrayAdder** | `Consumer<JavaScriptArray<U>>` | Lambda that modifies the array, see `JavaScriptArray` below. |

> **Info:** JavaScriptArray {#javascriptarray}
>
> `JavaScriptArray` allows building lambdas representing array manipulations for patches.
>
> | Method Signature | Return Type | Description |
> | - | :- | - |
> | **put(T item)** | `JavaScriptArray` | Allows adding `item` to an array. |
> | **put(T... items)** | `JavaScriptArray` | Items to be added to the array. |
> | **put(Collection\<T> items)** | `JavaScriptArray` | Items to be added to the array. |
> | **removeAt(int index)** | `JavaScriptArray` | Removes item in position `index` in array. |

## Session API using defer

The low level session api for patches uses the `session.advanced().defer` function that allows registering single or several commands.  
One of the possible commands is the `PatchCommandData`, describing single document patch command.  
The patch request will be sent to server only when calling `saveChanges`, this way it's possible to perform multiple operations in one request to the server.

`session.advanced().defer`

```java
void defer(ICommandData[] commands);
```

> **Info:** PatchCommandData {#patchcommanddata}
>
> | Constructor | | |
> | - | :- | - |
> | **id** | `String` | ID of the document to be patched. |
> | **changeVector** | `String` | \[Can be null] Change vector of the document to be patched, used to verify that the document was not changed before the patch reached it. |
> | **patch** | `PatchRequest` | Patch request to be performed on the document. |
> | **patchIfMissing** | `PatchRequest` | \[Can be null] Patch request to be performed if no document with the given ID was found. |

> **Info:** PatchRequest {#patchrequest}
>
> We highly recommend using scripts with parameters. This allows RavenDB to cache scripts and boost performance. Parameters can be accessed in the script through the "args" object, and passed using PatchRequest's "Values" parameter.
>
> | Members | | |
> | - | - | - |
> | **Script** | `String` | JavaScript code to be run. |
> | **Values** | `Map<String, Object>` | Parameters to be passed to the script. The parameters can be accessed using the '$' prefix. Parameter starting with a '$' will be used as is, without further concatenation . |

## Operations API

An operations interface that exposes the full functionality and allows performing ad-hoc patch operations without creating a session.

```java
PatchStatus send(PatchOperation operation);

PatchStatus send(PatchOperation operation, SessionInfo sessionInfo);

<TEntity> PatchOperation.Result<TEntity> send(Class<TEntity> entityClass, PatchOperation operation);

<TEntity> PatchOperation.Result<TEntity> send(Class<TEntity> entityClass, PatchOperation operation, SessionInfo sessionInfo);
```

> **Info:** PatchOperation {#patchoperation}
>
> | Constructor | | |
> | - | :- | - |
> | **id** | `String` | ID of the document to be patched. |
> | **changeVector** | `String` | \[Can be null] Change vector of the document to be patched, used to verify that the document was not changed before the patch reached it. |
> | **patch** | `PatchRequest` | Patch request to be performed on the document. |
> | **patchIfMissing** | `PatchRequest` | \[Can be null] Patch request to be performed if no document with the given ID was found. Will run only if no `changeVector` was passed. |
> | **skipPatchIfChangeVectorMismatch** | `boolean` | If false and `changeVector` has value, and document with that ID and change vector was not found, will throw exception. |

## List of Script Methods

This is a list of a few of the javascript methods that can be used in patch scripts. See the
more comprehensive list at [Knowledge Base: JavaScript Engine](https://docs.ravendb.net/6.2/server/kb/javascript-engine.md#predefined-javascript-functions).

| Method | Arguments | Description |
| - | - | - |
| **load** | `string` or `string[]` | Loads one or more documents into the context of the script by their document IDs |
| **loadPath** | A document and a path to an ID within that document | Loads a related document by the path to its ID |
| **del** | Document ID; change vector | Delete the given document by its ID. If you add the expected change vector and the document's current change vector does not match, the document will *not* be deleted. |
| **put** | Document ID; document; change vector | Create or overwrite a document with a specified ID and entity. If you try to overwrite an existing document and pass the expected change vector, the put will fail if the specified change vector does not match the document's current change vector. |
| **cmpxchg** | Key | Load a compare exchange value into the context of the script using its key |
| **getMetadata** | Document | Returns the document's metadata |
| **id** | Document | Returns the document's ID |
| **lastModified** | Document | Returns the `DateTime` of the most recent modification made to the given document |
| **counter** | Document; counter name | Returns the value of the specified counter in the specified document |
| **counterRaw** | Document; counter name | Returns the specified counter in the specified document as a key-value pair |
| **incrementCounter** | Document; counter name | Increases the value of the counter by one |
| **deleteCounter** | Document; counter name | Deletes the counter |

## Examples

### Change Field's Value

#### Session-syntax

```java
// change firstName to Robert
session
  .advanced()
  .patch("employees/1", "FirstName", "Robert");
```

#### Session-defer-syntax

```java
// change firstName to Robert
PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("this.FirstName = args.firstName");
patchRequest.setValues(Collections.singletonMap("firstName", "Robert"));
PatchCommandData patchCommandData = new PatchCommandData("employees/1", null, patchRequest, null);
session.advanced().defer(patchCommandData);

session.saveChanges();
```

#### Operations-syntax

```java
// change firstName to Robert
PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("this.FirstName = args.firstName;");
patchRequest.setValues(Collections.singletonMap("firstName", "Robert"));
PatchOperation patchOperation = new PatchOperation("employees/1", null, patchRequest);
store.operations().send(patchOperation);
```

### Change Values of Two Fields

#### Session-syntax

```java
// Modify FirstName to Robert and LastName to Carter in single request
// ===================================================================

// The two Patch operations below are sent via 'saveChanges()' which complete transactionally,
// as this call generates a single HTTP request to the database.
// Either both will succeed or both will be rolled back since they are applied within the same transaction.
// However, on the server side, the two Patch operations are still executed separately.
// To achieve atomicity at the level of a single server-side operation, use 'defer' or the operations syntax.

session.advanced().patch("employees/1", "FirstName", "Robert");
session.advanced().patch("employees/1", "LastName", "Carter");

session.saveChanges();
```

#### Session-defer-syntax

```java
// Change firstName to Robert and lastName to Carter in single request
// Note that here we do maintain the atomicity of the operation
PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("this.FirstName = args.firstName;" +
  "this.LastName = args.lastName");

Map<String, Object> values = new HashMap<>();
values.put("firstName", "Robert");
values.put("lastName", "Carter");
patchRequest.setValues(values);

session.advanced().defer(new PatchCommandData("employees/1", null, patchRequest, null));
session.saveChanges();
```

#### Operations-syntax

```java
// Change FirstName to Robert and LastName to Carter in single request
// Note that here we do maintain the atomicity of the operation
PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("this.FirstName = args.firstName; " +
  "this.LastName = args.lastName");

Map<String, Object> values = new HashMap<>();
values.put("firstName", "Robert");
values.put("lastName", "Carter");
patchRequest.setValues(values);

store.operations().send(new PatchOperation("employees/1", null, patchRequest));
```

### Increment Value

#### Session-syntax

```java
// increment UnitsInStock property value by 10
session.advanced().increment("products/1-A", "UnitsInStock", 10);

session.saveChanges();
```

#### Session-defer-syntax

```java
PatchRequest request = new PatchRequest();
request.setScript("this.UnitsInStock += args.unitsToAdd");
request.setValues(Collections.singletonMap("unitsToAdd", 10));

session.advanced().defer(
  new PatchCommandData("products/1-A", null, request, null));
session.saveChanges();
```

#### Operations-syntax

```java
PatchRequest request = new PatchRequest();
request.setScript("this.UnitsInStock += args.unitsToAdd");
request.setValues(Collections.singletonMap("unitsToAdd", 10));
store.operations().send(new PatchOperation("products/1-A", null, request));
```

### Add Item to Array

#### Session-syntax

```java
BlogComment comment = new BlogComment();
comment.setContent("Lore ipsum");
comment.setTitle("Some title");

session.advanced()
  .patch("blogposts/1", "comments", comments -> comments.add(comment));

session.saveChanges();
```

#### Session-defer-syntax

```java
// add a new comment to comments
BlogComment comment = new BlogComment();
comment.setContent("Lore ipsum");
comment.setTitle("Some title");

PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("this.comments.push(args.comment");
patchRequest.setValues(Collections.singletonMap("comment", comment));

session.advanced().defer(new PatchCommandData("blogposts/1", null, patchRequest, null));
session.saveChanges();
```

#### Operations-syntax

```java
// add a new comment to comments
BlogComment comment = new BlogComment();
comment.setContent("Lore ipsum");
comment.setTitle("Some title");

PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("this.comments.push(args.comment");
patchRequest.setValues(Collections.singletonMap("comment", comment));

store.operations().send(new PatchOperation("blogposts/1", null, patchRequest));
```

### Insert Item into Specific Position in Array

Inserting item into specific position is supported only by the non-typed APIs

#### Session-defer-syntax

```java
BlogComment comment = new BlogComment();
comment.setContent("Lore ipsum");
comment.setTitle("Some title");

PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("this.comments.splice(1, 0, args.comment)");
patchRequest.setValues(Collections.singletonMap("comment", comment));

session.advanced().defer(new PatchCommandData("blogposts/1", null, patchRequest, null));
session.saveChanges();
```

#### Operations-syntax

```java
BlogComment comment = new BlogComment();
comment.setContent("Lore ipsum");
comment.setTitle("Some title");

PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("this.comments.splice(1, 0, args.comment)");
patchRequest.setValues(Collections.singletonMap("comment", comment));

store.operations().send(new PatchOperation("blogposts/1", null, patchRequest));
```

### Modify Item in Specific Position in Array

Inserting item into specific position is supported only by the non-typed APIs

#### Session-defer-syntax

```java
// modify a comment at position 3 in Comments
BlogComment comment = new BlogComment();
comment.setContent("Lore ipsum");
comment.setTitle("Some title");

PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("this.comments.splice(3, 1, args.comment)");
patchRequest.setValues(Collections.singletonMap("comment", comment));

session.advanced().defer(new PatchCommandData("blogposts/1", null, patchRequest, null));
session.saveChanges();
```

#### Operations-syntax

```java
// modify a comment at position 3 in Comments
BlogComment comment = new BlogComment();
comment.setContent("Lore ipsum");
comment.setTitle("Some title");

PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("this.comments.splice(3, 1, args.comment)");
patchRequest.setValues(Collections.singletonMap("comment", comment));

store.operations().send(new PatchOperation("blogposts/1", null, patchRequest));
```

### Remove Items from Array

Filtering items from an array supported only by the non-typed APIs

#### Session-defer-syntax

```java
//filter out all comments of a blogpost which contains the word "wrong" in their contents
PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("this.comments = this.comments.filter(comment " +
  "=> !comment.content.includes(args.text));");
patchRequest.setValues(Collections.singletonMap("text", "wrong"));

session.advanced().defer(
  new PatchCommandData("blogposts/1", null, patchRequest, null));
session.saveChanges();
```

#### Operations-syntax

```java
// filter out all comments of a blogpost which contains the word "wrong" in their contents
PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("this.comments = this.comments.filter(comment " +
  "=> !comment.content.includes(args.text));");
patchRequest.setValues(Collections.singletonMap("text", "wrong"));

store.operations().send(new PatchOperation("blogposts/1", null, patchRequest));
```

### Loading Documents in a Script

Loading documents supported only by non-typed APIs

#### Session-defer-syntax

```java
// update product names in order, according to loaded product documents
PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("this.Lines.forEach(line => {" +
  " var productDoc = load(line.Product);" +
  " line.ProductName = productDoc.Name;" +
  "});");

session.advanced().defer(
  new PatchCommandData("orders/1", null, patchRequest, null));
session.saveChanges();
```

#### Operations-syntax

```java
// update product names in order, according to loaded product documents
PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("this.Lines.forEach(line => {" +
  " var productDoc = load(line.Product);" +
  " line.ProductName = productDoc.Name;" +
  "});");

store.operations().send(new PatchOperation("blogposts/1", null, patchRequest));
```

### Remove Property

Removing property supported only by the non-typed APIs

#### Session-defer-syntax

```java
// rename FirstName to Name

Map<String, Object> value = new HashMap<>();
value.put("old", "FirstName");
value.put("new", "Name");

PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("var firstName = this[args.rename.old];" +
  "delete this[args.rename.old];" +
  "this[args.rename.new] = firstName;");
patchRequest.setValues(Collections.singletonMap("rename", value));

session.advanced().defer(new PatchCommandData("employees/1", null, patchRequest, null));

session.saveChanges();
```

#### Operations-syntax

```java
Map<String, Object> value = new HashMap<>();
value.put("old", "FirstName");
value.put("new", "Name");

PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("var firstName = this[args.rename.old];" +
  "delete this[args.rename.old];" +
  "this[args.rename.new] = firstName;");
patchRequest.setValues(Collections.singletonMap("rename", value));

store.operations().send(new PatchOperation("employees/1", null, patchRequest));
```

### Rename Property

Renaming property supported only by the non-typed APIs

#### Session-defer-syntax

```java
// rename FirstName to Name

Map<String, Object> value = new HashMap<>();
value.put("old", "FirstName");
value.put("new", "Name");

PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("var firstName = this[args.rename.old];" +
  "delete this[args.rename.old];" +
  "this[args.rename.new] = firstName;");
patchRequest.setValues(Collections.singletonMap("rename", value));

session.advanced().defer(new PatchCommandData("employees/1", null, patchRequest, null));

session.saveChanges();
```

#### Operations-syntax

```java
Map<String, Object> value = new HashMap<>();
value.put("old", "FirstName");
value.put("new", "Name");

PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("var firstName = this[args.rename.old];" +
  "delete this[args.rename.old];" +
  "this[args.rename.new] = firstName;");
patchRequest.setValues(Collections.singletonMap("rename", value));

store.operations().send(new PatchOperation("employees/1", null, patchRequest));
```

### Add Document

Adding a new document is supported only by the non-typed APIs

#### Session-defer-syntax

```java
PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("put('orders/', { Employee: id(this) });");
PatchCommandData commandData =
  new PatchCommandData("employees/1-A", null, patchRequest, null);
session.advanced().defer(commandData);
session.saveChanges();
```

#### Operations-syntax

```java
PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("put('orders/', { Employee: id(this) });");

store.operations().send(new PatchOperation("employees/1-A", null, patchRequest));
```

### Clone Document

To clone a document via patching, use the `put` method within the patching script as follows:

#### Session-defer-syntax

```java
PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("put('employees/', this);");
PatchCommandData commandData =
  new PatchCommandData("employees/1-A", null, patchRequest, null);
session.advanced().defer(commandData);
session.saveChanges();
```

#### Operations-syntax

```java
PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("put('employees/', this);");

store.operations().send(new PatchOperation("employees/1-A", null, patchRequest));
```

> **Info**
>
> **Attachments, Counters, Time Series, and Revisions:**
>
> - When cloning a document via patching, only the document's fields are copied to the new document.
>   Attachments, counters, time series data, and revisions from the source document will Not be copied automatically.
> - To manage time series & counters via patching, you can use the pre-defined JavaScript methods listed here:
>   [Counters methods](https://docs.ravendb.net/6.2/server/kb/javascript-engine.md#counter-operations) & [Time series methods](https://docs.ravendb.net/6.2/server/kb/javascript-engine.md#time-series-operations).
> - Note: When [Cloning a document via the Studio](https://docs.ravendb.net/6.2/studio/database/documents/create-new-document.md#clone-an-existing-document),
>   attachments, counters, time Series, and revisions will be copied automatically.
>
> **Archived documents:**
>
> - If the source document is archived, the cloned document will Not be archived.

### Increment Counter

In order to increment or create a counter use \<code>incrementCounter\</code> method as follows

#### Session-defer-syntax

```java
HashMap<String, Object> scriptValues = new HashMap<>();
scriptValues.put("name", "likes");
scriptValues.put("val", 20);

PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("incrementCounter(this, args.name, args.val);");
patchRequest.setValues(scriptValues);

new PatchCommandData("orders/1-A", null, patchRequest, null);
session.saveChanges();
```

#### Operations-syntax

```java
HashMap<String, Object> scriptValues = new HashMap<>();
scriptValues.put("name", "likes");
scriptValues.put("val", -1);

PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("incrementCounter(this, args.name, args.val);");
patchRequest.setValues(scriptValues);

PatchOperation patchOperation = new PatchOperation("orders/1-A", null, patchRequest);
store.operations().send(patchOperation);
```

> **Info:** Method Overloading & Value restrictions {#method-overloading-value-restrictions}
>
> The method can be called by document ID or by document reference and the value can be negative

### Delete Counter

In order to delete a counter use \<code>deleteCounter\</code> method as follows

#### Session-defer-syntax

```java
HashMap<String, Object> scriptValues = new HashMap<>();
scriptValues.put("name", "Likes");

PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("deleteCounter(this, args.name);");
patchRequest.setValues(scriptValues);

new PatchCommandData("products/1-A", null, patchRequest, null);
session.saveChanges();
```

#### Operations-syntax

```java
HashMap<String, Object> scriptValues = new HashMap<>();
scriptValues.put("name", "Likes");

PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("deleteCounter(this, args.name);");
patchRequest.setValues(scriptValues);

PatchOperation patchOperation = new PatchOperation("products/1-A", null, patchRequest);
store.operations().send(patchOperation);
```

> **Info:** Method Overloading {#method-overloading}
>
> The method can be called by document ID or by document reference

### Get Counter

In order to get a counter while patching use \<code>counter\</code> method as follows

#### Session-defer-syntax

```java
HashMap<String, Object> scriptValues = new HashMap<>();
scriptValues.put("name", "Likes");

PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("var likes = counter(this.Company, args.name);\n" +
  "put('result/', {company: this.Company, likes: likes});");
patchRequest.setValues(scriptValues);

new PatchCommandData("orders/1-A", null, patchRequest, null);
session.saveChanges();
```

#### Operations-syntax

```java
HashMap<String, Object> scriptValues = new HashMap<>();
scriptValues.put("name", "Likes");

PatchRequest patchRequest = new PatchRequest();
patchRequest.setScript("var likes = counter(this.Company, args.name);\n" +
  "put('result/', {company: this.Company, likes: likes});");
patchRequest.setValues(scriptValues);

PatchOperation patchOperation = new PatchOperation("orders/1-A", null, patchRequest);
store.operations().send(patchOperation);
```

> **Info:** Method Overloading {#method-overloading-1}
>
> The method can be called by document ID or by document reference

## See also

- [Set based patch operation](https://docs.ravendb.net/6.2/client-api/operations/patching/set-based.java.md)
- [JavaScript engine](https://docs.ravendb.net/6.2/server/kb/javascript-engine.md)
- [Numbers in JavaScript engine](https://docs.ravendb.net/6.2/server/kb/numbers-in-ravendb.md#numbers-in-javascript-engine)
