---
title: "Creating a data subscription: API"
description: "Create and update RavenDB data subscriptions using the Client API, with filtering, projections, includes, and configurable subscription options."
url: "https://docs.ravendb.net/7.2/data-subscriptions/creating-subscription/creating-subscription_api"
version: "7.2"
language: "csharp"
---

# Creating a data subscription: API

> Client language: C#. Also available for [Java](https://docs.ravendb.net/7.2/data-subscriptions/creating-subscription/creating-subscription_api.java.md), [Node.js](https://docs.ravendb.net/7.2/data-subscriptions/creating-subscription/creating-subscription_api.nodejs.md), [Python](https://docs.ravendb.net/7.2/data-subscriptions/creating-subscription/creating-subscription_api.python.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**
>
> - A data subscription is a server-side task that sends documents matching a query to connected
>   clients ("workers"), in batches.
>
> - This page explains how to create and update a subscription using the Client API.  
>   You can also [create a subscription using Studio](https://docs.ravendb.net/7.2/data-subscriptions/creating-subscription/creating-subscription_studio.md).
>
> - A subscription's definition and its processing progress are kept on the cluster rather than on
>   a single node, and the cluster assigns one node to manage the task.
>
> - In this article:
>   - [Creating a subscription](#creating-a-subscription)
>     - [Create and CreateAsync](#create-and-createasync)
>     - [Create with typed expressions or with a raw RQL query](#create-with-typed-expressions-or-with-a-raw-rql-query)
>     - [Create vs Update](#create-vs-update)
>   - [Subscription name](#subscription-name)
>   - [Responsible node](#responsible-node)
>   - [Starting point](#starting-point)
>   - [Updating a subscription](#updating-a-subscription)
>     - [Changing a subscription's definition](#changing-a-subscriptions-definition)
>     - [Updating a subscription defined using typed expressions](#updating-a-subscription-defined-using-typed-expressions)
>     - [Creating a subscription via update](#creating-a-subscription-via-update)
>   - [Subscription query](#subscription-query)
>     - [Supported query parts](#supported-query-parts)
>     - [Unsupported RQL features](#unsupported-rql-features)
>     - [Paths in a subscription query](#paths-in-a-subscription-query)
>     - [Compare-exchange values in a subscription query](#compare-exchange-values-in-a-subscription-query)
>     - [Metadata in a subscription query](#metadata-in-a-subscription-query)
>   - [Projections](#projections)
>     - [Defining a projection](#defining-a-projection)
>     - [Processing projected objects](#processing-projected-objects)
>     - [Projecting into your own class or record](#projecting-into-your-own-class-or-record)
>     - [Including documents with a projection](#including-documents-with-a-projection)
>   - [Archived documents](#archived-documents)
>   - [Examples](#examples)
>     - [Sending an entire collection](#example-sending-an-entire-collection)
>     - [Filtering documents](#example-filtering-documents)
>     - [Filtering with a regular expression](#example-filtering-with-a-regular-expression)
>     - [Filtering by a compare-exchange value](#example-filtering-by-a-compare-exchange-value)
>     - [Scheduling document delivery using the `@refresh` metadata property](#example-scheduling-document-delivery-using-the-refresh-metadata-property)
>     - [Filtering and projecting fields](#example-filtering-and-projecting-fields)
>     - [Projecting into a record](#example-projecting-into-a-record)
>     - [Projecting from a related document](#example-projecting-from-a-related-document)
>     - [Including documents](#example-including-documents)
>     - [Including documents with a projection](#example-including-documents-with-a-projection)
>     - [Including counters](#example-including-counters)
>     - [Including time series](#example-including-time-series)
>     - [Updating an existing subscription](#example-updating-an-existing-subscription)
>     - [Updating a subscription defined using typed expressions](#example-updating-a-subscription-defined-using-typed-expressions)
>     - [Creating a subscription via update](#example-creating-a-subscription-via-update)
>   - [Syntax](#syntax)
>     - [Include builder](#include-builder)

## Creating a subscription {#creating-a-subscription}

To create a subscription, define the documents that the server should send to the worker, then register
this definition with the server using `store.Subscriptions.Create` or its asynchronous counterpart, `store.Subscriptions.CreateAsync`.

### `Create` and `CreateAsync`

[Create](#create) and [CreateAsync](#createasync) take the same arguments and an optional cancellation token.  
The examples on this page call `Create`. To create a subscription asynchronously, await `CreateAsync`.

#### Create

```csharp
// The server sends every document in the 'Orders' collection
// to any client that connects to this subscription.
subscriptionName = store.Subscriptions.Create<Order>();
```

#### CreateAsync

```csharp
// Creates the same subscription as the Create example,
// without blocking the calling thread while the server creates the subscription
subscriptionName = await store.Subscriptions.CreateAsync<Order>();
```

### `Create` with typed expressions or with a raw RQL query

You can use `Create` in two ways:

- **Typed expressions**  
  Write the definition as C# expressions, in one of these forms:
  - Pass a [SubscriptionCreationOptions\<T>](#classes) object whose `Filter`, `Projection`, and
    `Includes` expressions define the subscription.

    ```csharp
    subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions<Order>
    {
        Filter = x => x.Freight > 100
    });
    ```

  - Pass a lambda predicate directly to [Create\<T>](#create).

    ```csharp
    subscriptionName = store.Subscriptions.Create<Order>(x => x.Freight > 100);
    ```

- **A raw RQL (Raven Query Language) query**  
  Set the `Query` string in a [SubscriptionCreationOptions](#classes) object.

  ```csharp
  subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions
  {
      Query = "from Orders where Freight > 100"
  });
  ```

### `Create` vs `Update`

- [Create](#create)
  is meant to be called **once** per subscription.
  - Calling `Create` **without providing a name** creates a **new** subscription.  
    The server sets the subscription's name to the subscription's ID.
  - Calling `Create` with a **new name** creates a subscription that carries this name.
  - Calling `Create` with the name **of an existing subscription** throws an exception.

- [Update](#update)
  is meant to **modify** an existing subscription's definition, but can also **create** a subscription.  
  The method's behavior depends on the `CreateNew` property of the [SubscriptionUpdateOptions](#classes)
  object you pass to `Update`:

  - Set `CreateNew` to `true` to **create** the subscription if it doesn't exist yet,
    and **modify** the subscription if it already exists and its definition has changed.
  - Set `CreateNew` to `false` (the default) to **modify** an existing subscription.  
    If the subscription doesn't exist, `Update` throws an exception.

  See [Creating a subscription via update](#creating-a-subscription-via-update).

---

For filtering and includes, see the [Examples](#examples) below.  
For projections, see [Projections](#projections).  
To subscribe to document revisions, see [Revisions support](https://docs.ravendb.net/7.2/data-subscriptions/revisions-support.md).

## Subscription name {#subscription-name}

Every subscription has a name, which clients use to identify the subscription they want to
consume.  
If you do not provide a name when creating the subscription, the server generates one for you.  
To set your own:

```csharp
subscriptionName = store.Subscriptions.Create<Order>(new SubscriptionCreationOptions<Order>
{
    // Set a custom name for the subscription
    Name = "OrdersProcessingSubscription"
});
```

Setting your own name is useful for long-running batch processes: a readable name is easier to
work with in code, and you can reuse the same name across environments, as long as the
subscription is created in advance.

> **Info**
>
> A subscription name must be unique within its database. You cannot create two subscriptions with
> the same name in the same database.

## Responsible node {#responsible-node}

When a subscription is created, the cluster assigns one node to manage it. As long as this node is available,
it remains responsible for the subscription. If a worker connects to another node, that node will redirect it
to the responsible node.

If the responsible node goes down and your license includes
[highly available tasks](https://docs.ravendb.net/7.2/server/clustering/distribution/highly-available-tasks.md),
the task is reassigned to another node.  
While the assigned node is online, it remains the one managing the subscription.

To choose the responsible node yourself, set its tag in the `MentorNode` property:

```csharp
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions<Order>
{
    // Make node D responsible for the subscription
    MentorNode = "D"
});
```

Choosing the node manually lets you pick a server based on its hardware, proximity to the
consuming clients, or other considerations.

> **Note**
>
> To keep the subscription on the node you choose even if the node goes down, also set the `PinToMentorNode` property to `true`.  
> Pinning prevents another node from taking over the subscription, so processing resumes only when the chosen node
> is back online.

## Starting point {#starting-point}

The `ChangeVector` property of the [subscription creation options](#classes) sets the point from which the
subscription starts sending documents to the worker.  
`ChangeVector` accepts these values:

- **`"BeginningOfTime"`**  
  The subscription sends all documents matching its query, regardless of their creation or modification time.  
  The subscription behaves the same way when `ChangeVector` is not set.
- **`"LastDocument"`**  
  The subscription sends only documents created or modified after the subscription's creation.  
  This is useful for an ad-hoc process that needs only recent changes.
- **An actual change vector**  
  The subscription starts from the point this change vector marks.

```csharp
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions<Order>
{
    // Send only documents created or modified after the subscription's creation
    ChangeVector = "LastDocument"
});
```

To change the starting point of an existing subscription, see [Updating a subscription](#updating-a-subscription).

## Updating a subscription {#updating-a-subscription}

### Changing a subscription's definition

You can change an existing subscription's definition using the [Update](#update) method or its asynchronous counterpart,
[UpdateAsync](#updateasync).  
Pass a [SubscriptionUpdateOptions](#classes) object, which extends the creation options with two
additional fields, `Id` and `CreateNew`:

- **`Id`** targets the subscription by the ID the server assigned it at creation, instead of by
  name.
- **`CreateNew`** applies when the subscription you are updating does not exist.  
  Set it to `true` to create the subscription instead, or leave it `false`, the default, to
  throw an exception.  
  See [Creating a subscription via update](#creating-a-subscription-via-update).

> **Note**
>
> You cannot rename a subscription by providing its `Id` and a new `Name`.  
> Doing this keeps the existing subscription under its current name and adds a second subscription with the new name and the same ID.

Any property you leave unset in the `SubscriptionUpdateOptions` object keeps the subscription's current value.  
e.g., when you only change the query, the subscription keeps its name and processing progress:

```csharp
// Target the subscription by its Id and change only its query
store.Subscriptions.Update(new SubscriptionUpdateOptions
{
    Id = subscriptionId,
    Query = "from Orders where Freight > 200"
});
```

You can also move the subscription's [starting point](#starting-point) when you update it.  
Set `ChangeVector` to `"BeginningOfTime"` to process all matching documents again, or to `"LastDocument"` to send only
documents created or modified after the update.

For a full update example, see the [Examples](#examples) below.

### Updating a subscription defined using typed expressions

The `Update` method described above accepts a subscription's definition only as an RQL query, not as typed expressions.  
To update a subscription you defined using a [SubscriptionCreationOptions\<T>](#classes)
object, call the object's `ToSubscriptionCreationOptions` method.  
This method translates the object's `Filter`, `Projection`, and `Includes` expressions into an RQL query, and returns
the query in the `Query` property of a [SubscriptionCreationOptions](#classes) object.  
Pass the translated query to `Update`:

```csharp
var typedOptions = new SubscriptionCreationOptions<Order>
{
    Name = "OrdersProcessingSubscription",
    // The changed filter
    Filter = x => x.Lines.Sum(line => line.PricePerUnit * line.Quantity) > 200
};

// Translate the typed expressions into an RQL query, using the store's conventions
SubscriptionCreationOptions translated = typedOptions.ToSubscriptionCreationOptions(store.Conventions);

// Update the subscription with the translated query
store.Subscriptions.Update(new SubscriptionUpdateOptions
{
    Name = translated.Name,
    Query = translated.Query
});
```

Using the translated query, you can also check whether your typed expressions still match the subscription's current
definition (e.g., after you change a filter in your code), as shown in the [example below](#example-updating-a-subscription-defined-using-typed-expressions).

### Creating a subscription via update

Calling `Update` for a subscription that does not exist throws an exception.  
If, however, the `CreateNew` property of the [SubscriptionUpdateOptions](#classes) object that you pass to `Update` is set
to `true`, updating a subscription that does not exist creates the subscription using the name, query, and other options
set in the `SubscriptionUpdateOptions` object.

Creating a subscription via `Update` is useful when your application defines a subscription and passes the definition to
`Update` each time the application starts:

- The first time the application starts, `Update` **creates** the subscription.
- On later starts, `Update` **modifies** the subscription if the definition your application passes differs from the
  subscription's current definition (e.g., after you deploy a new version of the application with a changed query).  
  If there is no change in the subscription's definition, `Update` leaves the subscription as it is.

  > **Info**
  >
  > To keep the subscription's processing progress when your application restarts, do not set `ChangeVector` in the
  > options your application passes to `Update`.  
  > A set `ChangeVector` counts as a change in the subscription's definition, so `Update` moves the subscription's
  > [starting point](#starting-point) to the `ChangeVector` value each time the application starts.  
  > For example, with `ChangeVector` set to `"BeginningOfTime"`, the subscription sends all matching documents again
  > each time the application starts.

See [Example: Creating a subscription via update](#example-creating-a-subscription-via-update).

---

> **Note**
>
> If your application calls [Create](#create) rather than `Update` when the application starts:
>
> - Passing the subscription's name to `Create` **would fail on every start after the first**, since the server attempts to create a subscription that already exists.
> - Not passing a name to `Create` **would create a new subscription on every start**, and each new subscription would send the matching documents from the beginning.

## Subscription query {#subscription-query}

Every subscription is ultimately expressed as an RQL statement.  
Although a subscription query has an RQL-like structure, it supports only the `declare`, `from`, `as`,
`load`, `where`, `select`, and `include` keywords.  
To create a subscription over document revisions, see
[Revisions support](https://docs.ravendb.net/7.2/data-subscriptions/revisions-support.md).

### Supported query parts

A subscription query can have these parts:

- **A `declare` functions section**, as in ordinary RQL.  
  These functions can hold any JavaScript code, and support `load` and `include` operations.
- **A `from` clause** naming the document source, for example `from Orders`.  
  This clause can address only a collection; indexes are not supported.
- **A `where` clause** deciding the documents the server sends to the worker.  
  This clause supports:
  - **Comparison operators**: `=`, `==`, `!=`, `<`, `>`, `<=`, `>=`
  - **Logical operators**: `and`, `or`, `and not`
  - **The `in` operator**, e.g., `o.Company in ('companies/1-A', 'companies/2-A')`
  - **Methods**:
    - `startsWith(field, prefix)`
    - `endsWith(field, suffix)`
    - `regex(field, pattern)`
    - `exists(field)`
    - `intersect(condition, condition, ...)`
  - **JavaScript**: plain JavaScript expressions and calls to declared functions, so you can express complex filtering.
- **A `select` clause** defining the [projection](#projections).  
  This clause can call functions, allowing complex transformations.
- **An `include` clause** defining documents (by path), counters, or time series to include.

To learn about the JavaScript that subscription functions can use, see [JavaScript engine](https://docs.ravendb.net/7.2/server/kb/javascript-engine.md).

### Unsupported RQL features

A subscription query does not support:

- The `order by`, `group by`, and `update` clauses.  
  `select distinct`.
- Querying an index. The `from` clause can name only a collection.
- The `search`, `boost`, `lucene`, `exact`, `moreLikeThis`, and `vector.search` methods.  
  Spatial methods.
- The `now()` and `today()` functions.
- The `between` operator. Use `>=` and `<=` instead.
- Query parameters (e.g., `$min`).
- Including any object other than documents, counters, or time series.  
  For example, [compare-exchange items](https://docs.ravendb.net/7.2/compare-exchange/overview.md) (`include cmpxchg(...)`) and revisions
  (`include revisions(...)`) cannot be included.

The subscription does not apply `limit` and `filter` clauses, although it accepts a query that includes them.

### Paths in a subscription query

Paths in a subscription query are handled as JavaScript expressions rather than as regular RQL
paths.  
A query that in RQL would be written as:

```sql
from Orders as o
where o.Lines[].Product = "products/1-A"
```

is written in a subscription query as follows:

```sql
declare function filterLines(doc, productId)
{
    if (!!doc.Lines){
        return doc.Lines.filter(x => x.Product == productId).length > 0;
    }
    return false;
}

from Orders as o
where filterLines(o, "products/1-A")
```

### Compare-exchange values in a subscription query

A subscription's query cannot take parameters, so a value that the query compares documents against (e.g., a minimum freight) is
normally written into the query itself.  
Changing such a value then means updating the subscription, and the server disconnects the workers connected to the subscription
when the query changes.  
To change the value without updating the subscription, keep the value in a [compare-exchange item](https://docs.ravendb.net/7.2/compare-exchange/overview.md)
and read it in the query using the `cmpxchg` function.

The server reads the compare-exchange value each time the server evaluates the subscription's query for a document, so a change
to the value applies only to documents evaluated after the change.  
A change to the value does not make the server evaluate the query again for documents that were already evaluated.  
e.g., after you lower a minimum freight, an order that did not exceed the old minimum is sent only when the order is modified.

See [Example: Filtering by a compare-exchange value](#example-filtering-by-a-compare-exchange-value).

### Metadata in a subscription query

A subscription query can read the [metadata](https://docs.ravendb.net/7.2/client-api/session/how-to/get-and-modify-entity-metadata.md) of a document and
select documents by their metadata properties.  
e.g., the following subscription selects only orders whose metadata holds a `Priority` property with the value `High`.

```csharp
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions
{
    Query = "from Orders as o where o.'@metadata'.'Priority' = 'High'"
});
```

> **Note**
>
> Typed expressions cannot read a document's metadata, so metadata conditions can only be written in a raw RQL query.

Changing a document's metadata changes the document, so if the changed document matches the subscription's query, the subscription
sends the document to the worker.

To select documents whose metadata does not hold a specific property, use `not exists`
(see [Find documents that are missing a field](https://docs.ravendb.net/7.2/querying/filtering-query-results/filter-by-field-presence.md#find-documents-that-are-missing-a-field)).

```csharp
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions
{
    // A 'where' clause cannot start with 'not', so the clause starts with 'true and'
    Query = "from Orders as o where true and not exists(o.'@metadata'.'Priority')"
});
```

---

#### Scheduling document delivery using the `@refresh` metadata property

To have a subscription send a document to the worker at a time you choose (e.g., an email that the worker should send next week):

1. **Enable the *document refresh* feature for the database.**  
   The [*document refresh*](https://docs.ravendb.net/7.2/documents/document-refresh/client-api.md) feature removes the `@refresh` metadata property from a document
   once the time set by the property (e.g., `"@refresh": "2026-10-20T08:00:00.0000000Z"`) has passed, and saves the document.  
   To enable the *document refresh* feature, use the [ConfigureRefreshOperation](https://docs.ravendb.net/7.2/documents/document-refresh/client-api.md#configurerefreshoperation)
   operation or Studio's [Document Refresh](https://docs.ravendb.net/7.2/documents/document-refresh/document-refresh-view.md) view.  
   The *document refresh* feature periodically checks the database for documents to refresh (every 60 seconds by default),
   so a document is refreshed at the first check after the time set by its `@refresh` metadata property.

   > **Note**
   >
   > On a [Community license](https://ravendb.net/buy), the *document refresh* feature cannot check for documents to refresh more
   > often than every 36 hours.

2. **Have your subscription select only documents whose metadata does not hold the `@refresh` property.**

   ```csharp
   subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions
   {
       // A 'where' clause cannot start with 'not', so the clause starts with 'true and'
       Query = "from Emails as e where true and not exists(e.'@metadata'.'@refresh')"
   });
   ```

3. **Store each document with its `@refresh` metadata property set to the intended delivery time.**

   ```csharp
   using (var session = store.OpenSession())
   {
       var email = new Email { To = "customer@example.com", Subject = "Your order has shipped" };
       session.Store(email);

       // Have the subscription send the email to the worker 7 days from now
       session.Advanced.GetMetadataFor(email)["@refresh"] = DateTime.UtcNow.AddDays(7);

       session.SaveChanges();
   }
   ```

   As long as the document's metadata holds the `@refresh` property, the document does not match the query, and the subscription
   does not send the document.  
   At the first check after the time set by the `@refresh` metadata property, the *document refresh* feature removes the property
   and saves the document.  
   The document then matches the query, and the subscription sends the document to the worker.

To have the subscription send a document to the worker again later (e.g., when the email server is unavailable and sending the email
fails), set a new time in the document's `@refresh` metadata property in the worker's batch-processing code, and save the document.  
The document then does not match the query until the *document refresh* feature removes the new `@refresh` metadata property.

```csharp
using (var session = batch.OpenSession())
{
    foreach (var item in batch.Items)
    {
        // 'TrySendEmail' is your own method
        if (TrySendEmail(item.Result) == false)
        {
            // Sending failed: have the subscription send the email again 10 minutes from now
            session.Advanced.GetMetadataFor(item.Result)["@refresh"] = DateTime.UtcNow.AddMinutes(10);
        }
    }

    // Save the emails whose @refresh metadata property was set
    session.SaveChanges();
}
```

See [Example: Scheduling document delivery using the `@refresh` metadata property](#example-scheduling-document-delivery-using-the-refresh-metadata-property).

## Projections {#projections}

### Defining a projection

By default, a subscription sends each matching document to a worker in full.  
To send only the data the worker needs (e.g., an order's freight and shipping address), define a projection.  
The subscription then creates, for each matching document, an object that holds only the data the projection defines, and sends
this object to the worker in place of the document.  
Using a projection to send only the needed data also keeps the rest of each document from reaching the worker (see
[Security considerations](https://docs.ravendb.net/7.2/data-subscriptions/overview.md#security-considerations)).

You can define a projection in two ways:

- **A raw RQL query**  
  Add a `select` clause to the subscription's query.

  ```csharp
  subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions
  {
      Query = "from Orders as o select { Freight: o.Freight, ShipTo: o.ShipTo }"
  });
  ```

  The `select` clause must hold an object literal, as in the example above, or a call to a declared function that returns the
  projected object (e.g., `select projectOrder(o)`).  
  A list of fields, which ordinary RQL queries accept in a `select` clause (e.g., `select o.Freight, o.ShipTo`), will fail the
  creation of the subscription.  
  The `from` clause of a subscription query with a projection must define an alias for the collection (e.g., `from Orders as o`),
  or the creation of the subscription will fail.

- **Typed expressions**  
  Set the `Projection` expression of a [SubscriptionCreationOptions\<T>](#classes) object.

  ```csharp
  subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions<Order>
  {
      Projection = x => new { x.Freight, x.ShipTo }
  });
  ```

  The client translates the `Projection` expression into the `select` clause of the subscription's query, and writes the object
  literal and the alias for you, so the subscription's query meets the `select` and alias rules described above.

A projection can use:

- The document's fields, and values computed from these fields (e.g., an order's total).
- Data from [related documents](https://docs.ravendb.net/7.2/indexes/indexing-related-documents.md#what-are-related-documents), loaded using `RavenQuery.Load` in a typed expression, or using `load` in RQL.
- Counter values, using `counter` in RQL (e.g., `counter(o, 'Likes')`).
- Compare-exchange values, using `cmpxchg` in RQL
  (see [Compare-exchange values in a subscription query](#compare-exchange-values-in-a-subscription-query)).

> **Note**
>
> For each document that matches the query's `where` clause, the server creates the projected object and sends the projected
> object to the worker.  
> If the projection returns `null` instead of an object, the server skips the document, as the server skips documents that do not
> match the `where` clause.  
> e.g., if the function you call in the `select` clause returns `null` for orders that have no `ShipTo` field, the worker does not
> receive these orders, although the orders match the `where` clause.

See [Example: Filtering and projecting fields](#example-filtering-and-projecting-fields) and
[Example: Projecting from a related document](#example-projecting-from-a-related-document).

### Processing projected objects

The subscription sends the projected objects to the worker in batches, and each item of a batch holds one projected object
(see [SubscriptionBatch\<T>.Item](https://docs.ravendb.net/7.2/data-subscriptions/consuming-subscription.md#classes)):

- The item's `Result` property holds the projected object.
- The item's `Id` property holds the ID of the document the projected object was created from (the **source document**).
- The item's `Projection` property is `true`.
- The item's `Metadata` property holds **the metadata of the projected object**, not the metadata of the source document.

To have the worker receive the metadata of the source document, include this metadata in the projection: use `getMetadata(o)` to
include the whole metadata, or `o['@metadata']['trace.id']` to include a single metadata property you set yourself (e.g., `trace.id`).  
In a `select` clause, write the metadata path using brackets, since the RQL form `o.'@metadata'.'trace.id'` will fail the creation of
the subscription.

```csharp
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions
{
    // Include the source document's whole metadata, and a single metadata property
    Query = @"from Orders as o
              select {
                  Freight: o.Freight,
                  Metadata: getMetadata(o),
                  TraceId: o['@metadata']['trace.id']
              }"
});
```

> **Note**
>
> Typed expressions cannot read a document's metadata, so a projection that includes metadata can only be written in a raw RQL query.

---

#### Modifying source documents

A session that you open using the batch's `OpenSession` method
(see [Example: Processing documents in a session](https://docs.ravendb.net/7.2/data-subscriptions/consuming-subscription.md#example-processing-documents-in-a-session)) tracks the documents
the batch holds, but does not track projected objects.  
Changes you make to a projected object are therefore not saved when you call `SaveChanges`.

To modify a source document, load the source document in the session using the item's `Id`, change the loaded document,
and call `SaveChanges`.  
Since the session does not hold the source document, loading the source document sends a request to the server.

```csharp
using (var session = batch.OpenSession())
{
    foreach (var item in batch.Items)
    {
        // Load the source document of the projected object
        var order = session.Load<Order>(item.Id);
        // Set the field that the subscription's query uses to exclude handled orders
        order.ShippedAt = DateTime.UtcNow;
    }

    // Save the modified source documents
    session.SaveChanges();
}
```

> **Note**
>
> Saving a modified source document makes the subscription send the document again if the document still matches the
> subscription's query (see [Processing order and re-sending](https://docs.ravendb.net/7.2/data-subscriptions/overview.md#processing-order-and-re-sending)).  
> To keep the worker from processing the same documents again, define the query to exclude the documents the worker has already
> handled.
>
> e.g., the sample above sets the `ShippedAt` field of each order the worker handles.  
> The following subscription selects only orders whose `ShippedAt` is `null`, so an order that the worker has saved with a
> shipping date no longer matches the subscription's query and is not sent again:
>
> ```csharp
> subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions
> {
>     Query = "from Orders as o where o.ShippedAt = null select { Freight: o.Freight }"
> });
> ```

### Projecting into your own class or record

The `Projection` expression of a [SubscriptionCreationOptions\<T>](#classes) object can create an anonymous object, or an
object of a class or record you define (e.g., `OrderTotal`).  
To have the worker receive the projected items as objects of this class or record, pass the class or record as the type parameter
of `GetSubscriptionWorker` when you [create the worker](https://docs.ravendb.net/7.2/data-subscriptions/consuming-subscription.md#creating-a-subscription-worker)
(e.g., `GetSubscriptionWorker<OrderTotal>`).

Projecting into a class or record you define has two advantages over projecting into an anonymous object:

- **Field names checked when you build the application**  
  The C# compiler checks the worker's use of the projected fields (e.g., `orderTotal.Total`), so a misspelled field name is
  reported when you build the application.  
  If the projection creates an anonymous object, the worker can receive the projected items as
  [dynamic objects](https://docs.ravendb.net/7.2/data-subscriptions/consuming-subscription.md#example-processing-dynamic-objects), whose field names the C# compiler cannot check, so a misspelled
  field name is found only when the code runs.
- **One definition for the projection and the worker**  
  The projection and the worker both use the class or record, so the projected fields are defined in one place.  
  With an anonymous object in the projection, a class of your own for the worker (e.g., `GetSubscriptionWorker<OrderSummary>`)
  defines the fields a second time, so every change must be made in both definitions.

---

#### Creating the object in the projection

To create an object of a class or record you define, use an object initializer, or call a constructor.  
When you call a constructor, each of its parameters must have the name of a public property of the class or record (case is ignored)
and a type compatible with the property's type.  
The client names the fields of the projected object after these properties.

e.g., the constructor parameters of the following class match the class's properties, so a projection can create objects of the
class by calling the constructor:

```csharp
public class OrderInfo
{
    // The 'orderId' parameter matches the 'OrderId' property (case is ignored)
    public OrderInfo(string orderId, decimal freight)
    {
        OrderId = orderId;
        Freight = freight;
    }

    public string OrderId { get; }
    public decimal Freight { get; }
}
```

```csharp
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions<Order>
{
    // Create the projected object by calling the constructor
    Projection = x => new OrderInfo(x.Id, x.Freight)
});
```

The projected object holds the fields `OrderId` and `Freight`.

A positional record (a record whose properties are defined by its constructor's parameters) can be created only by calling the
record's constructor, and the record's parameters always match its properties.

See [Example: Projecting into a record](#example-projecting-into-a-record).

### Including documents with a projection

A subscription can include related documents in the batches it sends (e.g., the `Company` document that an order's `Company`
field refers to), so the worker can read these documents without requesting them from the server.  
When the subscription's query has a projection, the server looks for the fields that hold the IDs of the documents to include in
the projected object, not in the source document.  
The projection must therefore contain these fields (e.g., `Company`), or the subscription includes no documents.

See [Example: Including documents with a projection](#example-including-documents-with-a-projection).

## Archived documents {#archived-documents}

You can schedule documents to be [archived](https://docs.ravendb.net/7.2/data-archival/overview.md) (e.g., orders you no longer process regularly).  
RavenDB compresses archived documents to save disk space.  
By default, a subscription sends only non-archived documents to the worker.

To have the subscription send archived documents as well, or only archived documents, set the
`ArchivedDataProcessingBehavior` property of the [subscription creation options](#classes)
when you create the subscription:

- **`ExcludeArchived`**  
  The subscription selects only non-archived documents.
- **`IncludeArchived`**  
  The subscription selects both archived and non-archived documents.  
  e.g., for a process that handles every order, including archived orders.
- **`ArchivedOnly`**  
  The subscription selects only archived documents.  
  e.g., for a process that copies archived orders to an external storage system.

```csharp
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions<Order>
{
    // Send only archived documents to the worker
    ArchivedDataProcessingBehavior = ArchivedDataProcessingBehavior.ArchivedOnly
});
```

If you leave `ArchivedDataProcessingBehavior` unset, the subscription uses the handling set by the
[Subscriptions.ArchivedDataProcessingBehavior](https://docs.ravendb.net/7.2/data-subscriptions/configuration.md#subscriptionsarchiveddataprocessingbehavior) configuration key (`ExcludeArchived` by default).  
The subscription keeps the key's value from the time the subscription is created, so a later change to the key
does not affect existing subscriptions.

> **Note**
>
> - The [Update](#update) method does not change the subscription's handling of archived documents, even if you set
>   `ArchivedDataProcessingBehavior` in the `SubscriptionUpdateOptions` object.  
>   To change an existing subscription's handling of archived documents, edit the subscription task in Studio's
>   [Ongoing Tasks view](https://docs.ravendb.net/7.2/studio/database/tasks/ongoing-tasks/general-info.md#the-ongoing-tasks-list), and set the task's **Archived Data Processing Behavior** option.  
>   This option is described in [Creating a data subscription: Studio](https://docs.ravendb.net/7.2/data-subscriptions/creating-subscription/creating-subscription_studio.md#defining-the-subscription-task).
> - A subscription to [document revisions](https://docs.ravendb.net/7.2/data-subscriptions/revisions-support.md) **ignores** `ArchivedDataProcessingBehavior` and sends the revisions of archived and non-archived documents alike.
> - On a [sharded database](https://docs.ravendb.net/7.2/sharding/subscriptions.md#unsupported-features), a subscription **ignores** both `ArchivedDataProcessingBehavior` and the
>   **Archived Data Processing Behavior** option set in Studio, and uses the handling set by the `Subscriptions.ArchivedDataProcessingBehavior` configuration key.  
>   Unlike on a non-sharded database, a later change to the configuration key **does** affect existing subscriptions.

To learn more about a subscription's handling of archived documents, see [Data archival: Archived documents and subscriptions](https://docs.ravendb.net/7.2/data-archival/archived-documents-and-other-features.md#archived-documents-and-subscriptions).

## Examples {#examples}

### Example: Sending an entire collection

In this example, the subscription sends to the worker every document in the `Orders` collection, with no filter or projection.

#### Generic API

```csharp
subscriptionName = store.Subscriptions.Create<Order>();
```

#### RQL

```csharp
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions()
{
    Query = "from Orders"
});
```

### Example: Filtering documents

In this example, the subscription sends to the worker only `Orders` whose total revenue exceeds 100.  
The server evaluates the filter and sends just the matching documents.

#### Generic API

```csharp
subscriptionName = store.Subscriptions.Create<Order>(x =>
    // Only documents matching this filter will be sent
    x.Lines.Sum(line => line.PricePerUnit * line.Quantity) > 100);
```

#### RQL

```csharp
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions()
{
    Query = @"declare function getOrderLinesSum(doc) {
                  var sum = 0;
                  for (var i in doc.Lines) {
                      sum += doc.Lines[i].PricePerUnit * doc.Lines[i].Quantity;
                  }
                  return sum;
              }

              from Orders as o
              where getOrderLinesSum(o) > 100"
});
```

### Example: Filtering with a regular expression

In this example, the subscription filters documents with a regular expression.  
Use `Regex.IsMatch` inside the filter expression to match a field against a pattern on the
server, here `Orders` whose `ShipTo.City` starts with `New`.

#### Generic API

```csharp
// Filter using Regex.IsMatch in the subscription's LINQ filter
subscriptionName = store.Subscriptions.Create<Order>(x =>
    Regex.IsMatch(x.ShipTo.City, "^New"));
```

#### RQL

```csharp
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions()
{
    Query = @"from Orders
              where regex(ShipTo.City, '^New')"
});
```

Pass supported `RegexOptions` as a third argument:

```csharp
// Filter with case-insensitive regex matching
subscriptionName = store.Subscriptions.Create<Order>(x =>
    Regex.IsMatch(x.ShipTo.City, "^new", RegexOptions.IgnoreCase));
```

> **Note**
>
> The following `RegexOptions` are supported: `RegexOptions.IgnoreCase`, `RegexOptions.Multiline`,
> and `RegexOptions.Singleline`.  
> Other values, such as `Compiled` or `ExplicitCapture`, and the timeout overload are not
> supported and throw a `NotSupportedException`.  
> The pattern must be a constant expression; it cannot be a value computed at runtime from
> document fields.

### Example: Filtering by a compare-exchange value

In this example, the subscription sends to the worker only `Orders` whose `Freight` exceeds the minimum freight kept in the
[compare-exchange item](https://docs.ravendb.net/7.2/compare-exchange/overview.md) `config/minFreight` (e.g., `100`).  
The query reads the item's value using the `cmpxchg` function (see [Compare-exchange values in a subscription query](#compare-exchange-values-in-a-subscription-query)).

```csharp
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions()
{
    Query = @"from Orders as o
              where o.Freight > cmpxchg('config/minFreight')"
});
```

### Example: Scheduling document delivery using the `@refresh` metadata property

In this example, the subscription sends each email to the worker once the time set in the email's `@refresh` metadata property has
passed, and the worker sets a new time in this property for each email the worker fails to send.  
For an explanation of this use of the `@refresh` metadata property, see
[Scheduling document delivery using the `@refresh` metadata property](#scheduling-document-delivery-using-the-refresh-metadata-property).

#### Subscription side

```csharp
// Enable the document refresh feature for the database
store.Maintenance.Send(new ConfigureRefreshOperation(new RefreshConfiguration
{
    Disabled = false
}));

// Create a subscription that selects only emails whose metadata does not hold the @refresh property
store.Subscriptions.Create(new SubscriptionCreationOptions
{
    Name = "ScheduledEmails",
    // A 'where' clause cannot start with 'not', so the clause starts with 'true and'
    Query = "from Emails as e where true and not exists(e.'@metadata'.'@refresh')"
});

// Store an email, and schedule its delivery to the worker 7 days from now
using (var session = store.OpenSession())
{
    var email = new Email { To = "customer@example.com", Subject = "Your order has shipped" };
    session.Store(email);
    session.Advanced.GetMetadataFor(email)["@refresh"] = DateTime.UtcNow.AddDays(7);
    session.SaveChanges();
}
```

#### Worker side

```csharp
var worker = store.Subscriptions.GetSubscriptionWorker<Email>("ScheduledEmails");

await worker.Run(batch =>
{
    using (var session = batch.OpenSession())
    {
        foreach (var item in batch.Items)
        {
            // 'TrySendEmail' is your own method
            if (TrySendEmail(item.Result) == false)
            {
                // Sending failed: have the subscription send the email again 10 minutes from now
                session.Advanced.GetMetadataFor(item.Result)["@refresh"] = DateTime.UtcNow.AddMinutes(10);
            }
        }

        // Save the emails whose @refresh metadata property was set
        session.SaveChanges();
    }
});
```

### Example: Filtering and projecting fields

In this example, the subscription filters `Orders` by total revenue, and projects only two fields into each item
sent to the client: the document ID and the computed total.

#### Generic API

```csharp
subscriptionName = store.Subscriptions.Create<Order>(new SubscriptionCreationOptions<Order>()
{
    // The subscription criteria:
    Filter = x => x.Lines.Sum(line => line.PricePerUnit * line.Quantity) > 100,

    // The object properties that will be sent for each matching document:
    Projection = x => new
    {
        Id = x.Id,
        Total = x.Lines.Sum(line => line.PricePerUnit * line.Quantity)
    }
});
```

#### RQL

```csharp
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions()
{
    Query = @"declare function getOrderLinesSum(doc) {
                  var sum = 0;
                  for (var i in doc.Lines) {
                      sum += doc.Lines[i].PricePerUnit * doc.Lines[i].Quantity;
                  }
                  return sum;
              }

              declare function projectOrder(doc) {
                  return {
                      Id: id(doc),
                      Total: getOrderLinesSum(doc)
                  };
              }

              from Orders as o
              where getOrderLinesSum(o) > 100
              select projectOrder(o)"
});
```

### Example: Projecting into a record

In this example, the subscription projects each `Order` into an `OrderTotal` positional record by calling the record's
constructor, and the worker receives each projected item as an `OrderTotal` object (see
[Projecting into your own class or record](#projecting-into-your-own-class-or-record)).

```csharp
// A positional record: its parameters define both its constructor
// and its properties, which are the projected fields
public record OrderTotal(string OrderId, decimal Total);
```

```csharp
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions<Order>
{
    Filter = x => x.Lines.Sum(line => line.PricePerUnit * line.Quantity) > 100,

    // Create the projected object using the record's constructor
    Projection = x => new OrderTotal(x.Id, x.Lines.Sum(line => line.PricePerUnit * line.Quantity))
});

// Get a worker that receives the projected items as OrderTotal objects
SubscriptionWorker<OrderTotal> worker = store.Subscriptions.GetSubscriptionWorker<OrderTotal>(subscriptionName);

var subscriptionRuntimeTask = worker.Run(batch =>
{
    foreach (var item in batch.Items)
    {
        OrderTotal orderTotal = item.Result;
        Console.WriteLine($"{orderTotal.OrderId}: {orderTotal.Total}");
    }
});
```

### Example: Projecting from a related document

In this example, the subscription projects fields from each `Order` and also pulls data from a
[related document](https://docs.ravendb.net/7.2/indexes/indexing-related-documents.md#what-are-related-documents),
loaded using `Load`.

#### Generic API

```csharp
subscriptionName = store.Subscriptions.Create<Order>(
    new SubscriptionCreationOptions<Order>()
    {
        // The subscription criteria:
        Filter = x => x.Lines.Sum(line => line.PricePerUnit * line.Quantity) > 100,

        // The object properties that will be sent for each matching document:
        Projection = x => new
        {
            Id = x.Id,
            Total = x.Lines.Sum(line => line.PricePerUnit * line.Quantity),
            ShipTo = x.ShipTo,

            // 'Load' the related Employee document and use its data in the projection
            // Both Load calls resolve to a single server-side load
            EmployeeName = RavenQuery.Load<Employee>(x.Employee).FirstName + " " +
                           RavenQuery.Load<Employee>(x.Employee).LastName
        }
    });
```

#### RQL

```csharp
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions()
{
    Query = @"declare function getOrderLinesSum(doc) {
                  var sum = 0;
                  for (var i in doc.Lines) {
                      sum += doc.Lines[i].PricePerUnit * doc.Lines[i].Quantity;
                  }
                  return sum;
              }

              declare function projectOrder(doc) {
                  var employee = load(doc.Employee);
                  return {
                      Id: id(doc),
                      Total: getOrderLinesSum(doc),
                      ShipTo: doc.ShipTo,
                      EmployeeName: employee.FirstName + ' ' + employee.LastName
                  };
              }

              from Orders as o
              where getOrderLinesSum(o) > 100
              select projectOrder(o)"
});
```

### Example: Including documents

In this example, the subscription sends every `Order` and includes the `Product` documents related to the order
in the same batch, so the consuming worker can later read each `Product` without an extra call to
the server.

#### Builder

```csharp
subscriptionName = store.Subscriptions.Create<Order>(new SubscriptionCreationOptions<Order>()
{
    Includes = builder => builder
         // The documents whose IDs are in each order line's 'Product' property
         // will be included in the batch
        .IncludeDocuments(x => x.Lines.Select(y => y.Product))
});
```

#### RQL path

```csharp
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions()
{
    Query = @"from Orders include Lines[].Product"
});
```

#### RQL JavaScript

```csharp
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions()
{
    Query = @"declare function includeProducts(doc) {
                  let linesCount = doc.Lines.length;

                  for (let i = 0; i < linesCount; i++) {
                      include(doc.Lines[i].Product);
                  }

                  return doc;
              }

              from Orders as o select includeProducts(o)"
});
```

To include related documents, assign a function to the `Includes` property of the `SubscriptionCreationOptions<T>` object.  
The function receives an `ISubscriptionIncludeBuilder` object and calls the builder's `IncludeDocuments` method.  
Calls to the builder's methods can be chained.  
For the syntax of the builder's methods that include documents, see
[Include builder: documents](#include-builder-documents).

In RQL, write the include in one of two ways: append the `include` keyword followed by the paths
to the fields holding the IDs to include (preferred, for both clarity and slightly better
performance), or call `include` inside a JavaScript function invoked from the `select` clause.

> **Info**
>
> When you include documents alongside a projection, the `include` resolves paths against the
> projected fields rather than the original document (see [Example: Including documents with a projection](#example-including-documents-with-a-projection)).

### Example: Including documents with a projection

In this example, the subscription sends a projection of each `Order` and includes the `Company` document related to the order
(see [Including documents with a projection](#including-documents-with-a-projection)).  
The projection contains the order's `Company` field, which holds the ID of the document to include:

```csharp
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions()
{
    Query = @"from Orders as o
              select { Freight: o.Freight, Company: o.Company }
              include Company"
});
```

If the projection does not contain the `Company` field (e.g., `select { Freight: o.Freight }`), the subscription includes no
`Company` documents, even if the `include` clause names the field through the query's alias (`include o.Company`).

### Example: Including counters

In this example, the subscription sends to the worker every `Order` and includes the values of the
named counters in the batch.

#### Builder

```csharp
subscriptionName = store.Subscriptions.Create<Order>(new SubscriptionCreationOptions<Order>()
{
    Includes = builder => builder
         // Values for the specified counters will be included in the batch
        .IncludeCounters(new[] { "Pros", "Cons" })
});
```

#### RQL

```csharp
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions()
{
    Query = @"from Orders include counters('Pros'), counters('Cons')"
});
```

For the syntax of the builder's methods that include counters, see
[Include builder: counters](#include-builder-counters).

Include builder methods can be **chained**.  
e.g., the following subscription includes several counters and a related document.

```csharp
subscriptionName = store.Subscriptions.Create<Order>(new SubscriptionCreationOptions<Order>()
{
    Includes = builder => builder
        .IncludeCounter("Likes")
        .IncludeCounters(new[] { "Pros", "Cons" })
        .IncludeDocuments("Employee")
});
```

> **Note**
>
> Changing the value of an existing counter after the document was sent does not trigger a
> re-send.  
> Adding a new counter to the document, or removing one, does trigger re-sending the document.

### Example: Including time series

In this example, the subscription sends every `Order` and includes time-series entries for each
document in the batch, so the worker has those entries without issuing additional requests to the server.

#### Builder

```csharp
subscriptionName = store.Subscriptions.Create<Order>(new SubscriptionCreationOptions<Order>()
{
    Includes = builder => builder
        // Include the last 10 entries of each document's "HeartRate" time series
        .IncludeTimeSeries("HeartRate", TimeSeriesRangeType.Last, 10)
});
```

#### RQL

```csharp
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions()
{
    Query = @"from Orders include timeseries('HeartRate', last(10))"
});
```

In RQL, use the `last` method to define the entries to include: a number of the latest entries (e.g., `last(10)`), or a
period that ends at the time series' latest entry (e.g., `last(5, 'minutes')`).  
To include these entries from all of the document's time series, omit the time series name (e.g., `timeseries(last(10))`).  
A range defined by a start time and an end time is not supported.

For the syntax of the builder's methods that include time series, see
[Include builder: time series](#include-builder-time-series).

### Example: Updating an existing subscription

You can change a subscription's definition after creation. Target it by name, or by the ID the
server assigned it at creation.

Update by name, here changing the filter query of a subscription named "my subscription":

```csharp
subscriptionName = store.Subscriptions.Update(new SubscriptionUpdateOptions()
{
    // Specify the subscription you wish to modify
    Name = "my subscription",

    // Provide a new query
    Query = "from Products where PricePerUnit > 50"
});
```

Update by ID, retrieving the ID from the subscription's state:

```csharp
// Get the subscription's ID
SubscriptionState mySubscription = store.Subscriptions.GetSubscriptionState("my subscription");
long subscriptionId = mySubscription.SubscriptionId;

// Update the subscription
subscriptionName = store.Subscriptions.Update(new SubscriptionUpdateOptions()
{
    Id = subscriptionId,
    Query = "from Products where PricePerUnit > 50"
});
```

### Example: Updating a subscription defined using typed expressions

In this example, the application compares the RQL query translated from its typed expressions with the subscription's
current query, and updates the subscription only if the two queries differ.  
The application retrieves the current query from the server using [GetSubscriptionState](https://docs.ravendb.net/7.2/data-subscriptions/maintenance-operations.md#getting-a-subscription-state).  
An application can run this check at startup, e.g., after a new version of the application has changed the subscription's filter.

```csharp
// The subscription's definition, as the application's code defines it now
var typedOptions = new SubscriptionCreationOptions<Order>
{
    Name = "OrdersProcessingSubscription",
    Filter = x => x.Lines.Sum(line => line.PricePerUnit * line.Quantity) > 200
};

// Translate the typed expressions into an RQL query, using the store's conventions
SubscriptionCreationOptions translated = typedOptions.ToSubscriptionCreationOptions(store.Conventions);

// Get the subscription's current query from the server
SubscriptionState state = store.Subscriptions.GetSubscriptionState(translated.Name);

// Update the subscription only if its current query differs from the translated query
if (state.Query != translated.Query)
{
    store.Subscriptions.Update(new SubscriptionUpdateOptions
    {
        Name = translated.Name,
        Query = translated.Query
    });
}
```

---

> **Note**
>
> When the typed expressions include a filter, a projection, or includes, the translated query spans several lines, and the characters
> that end each line (the **line breaks**) follow the format of the operating system that runs the translation
> (`\r\n` on Windows, `\n` on Linux).  
> If the subscription's current query was translated on another operating system, the two queries differ in their
> line breaks even when the typed expressions are the same, so the subscription is updated although its definition has not changed.  
> The server then disconnects the workers connected to the subscription, and the workers reconnect to it.  
> The subscription keeps its processing progress.  
> To avoid an unneeded update, compare the queries with their line breaks normalized:
>
> ```csharp
> if (state.Query.Replace("\r\n", "\n") != translated.Query.Replace("\r\n", "\n"))
> ```

### Example: Creating a subscription via update

In this example, `Update` creates a subscription named "my subscription" if the subscription does not exist yet, using the
query set in the `SubscriptionUpdateOptions` object.  
If the subscription already exists, `Update` replaces the subscription's current query with the query set in
the `SubscriptionUpdateOptions` object, unless the two queries are the same.  
For an explanation of this use of `Update`, see [Creating a subscription via update](#creating-a-subscription-via-update).

```csharp
subscriptionName = store.Subscriptions.Update(new SubscriptionUpdateOptions()
{
    Name = "my subscription",
    Query = "from Products where PricePerUnit > 20",

    // Set to true so that a new subscription is created
    // if a subscription named "my subscription" does not exist
    CreateNew = true
});
```

## Syntax {#syntax}

### Methods

#### Create

##### Create

Create a subscription on the server.

```csharp
string Create(SubscriptionCreationOptions options,
              string database = null);

string Create<T>(SubscriptionCreationOptions options = null,
                 string database = null);

string Create<T>(SubscriptionCreationOptions<T> options,
                 string database = null);

string Create<T>(Expression<Func<T, bool>> predicate,
                 PredicateSubscriptionCreationOptions options = null,
                 string database = null);
```

##### CreateAsync

Create a subscription on the server asynchronously.

```csharp
Task<string> CreateAsync(SubscriptionCreationOptions options,
                         string database = null,
                         CancellationToken token = default);

Task<string> CreateAsync<T>(SubscriptionCreationOptions options = null,
                            string database = null,
                            CancellationToken token = default);

Task<string> CreateAsync<T>(SubscriptionCreationOptions<T> options,
                            string database = null,
                            CancellationToken token = default);

Task<string> CreateAsync<T>(Expression<Func<T, bool>> predicate,
                            PredicateSubscriptionCreationOptions options = null,
                            string database = null,
                            CancellationToken token = default);
```

| Parameter | Type | Description |
| - | - | - |
| **predicate** | `Expression<Func<T, bool>>` | A lambda expression returning a boolean that defines the subscription's filter. |
| **options** | `SubscriptionCreationOptions<T>`, `SubscriptionCreationOptions`, or `PredicateSubscriptionCreationOptions` | The subscription creation options. See the [Classes](#classes) below. |
| **database** | `string` | The database where the subscription is created. If `null`, the document store's default database is used. |
| **token** | `CancellationToken` | `CreateAsync` only.<br />A token used to cancel the creation operation. |

| Return value | |
| - | - |
| `string` (`Task<string>` for `CreateAsync`) | The name of the created subscription. If a name was provided in the options it is returned; otherwise the server generates a unique name. |

#### Update

##### Update

Update an existing subscription's definition.

```csharp
string Update(SubscriptionUpdateOptions options, string database = null);
```

##### UpdateAsync

Update an existing subscription's definition asynchronously.

```csharp
Task<string> UpdateAsync(SubscriptionUpdateOptions options, string database = null,
                         CancellationToken token = default);
```

| Parameter | Type | Description |
| - | - | - |
| **options** | `SubscriptionUpdateOptions` | The subscription update options. See the [Classes](#classes) below. |
| **database** | `string` | The database where the subscription resides. If `null`, the document store's default database is used. |
| **token** | `CancellationToken` | `UpdateAsync` only.<br />A token used to cancel the update operation. |

| Return value | |
| - | - |
| `string` (`Task<string>` for `UpdateAsync`) | The name of the updated subscription. |

#### ToSubscriptionCreationOptions

Translate the typed expressions of a `SubscriptionCreationOptions<T>` object into an RQL query, without contacting the server.

```csharp
SubscriptionCreationOptions ToSubscriptionCreationOptions(DocumentConventions conventions);
```

| Parameter | Type | Description |
| - | - | - |
| **conventions** | `DocumentConventions` | The conventions used in the translation (e.g., to resolve the collection name of `T`).<br />Pass the document store's conventions, `store.Conventions`. |

| Return value | |
| - | - |
| `SubscriptionCreationOptions` | A new options object whose `Query` holds the translated RQL query.<br />The new object's `Name`, `ChangeVector`, `MentorNode`, `PinToMentorNode`, `Disabled`, and `ArchivedDataProcessingBehavior` are copied from the `SubscriptionCreationOptions<T>` object. |

### Classes

#### SubscriptionCreationOptions\<T>

```csharp
public sealed class SubscriptionCreationOptions<T>
{
    public string Name { get; set; }
    public Expression<Func<T, bool>> Filter { get; set; }
    public Expression<Func<T, object>> Projection { get; set; }
    public Action<ISubscriptionIncludeBuilder<T>> Includes { get; set; }
    public string ChangeVector { get; set; }
    public bool Disabled { get; set; }
    public string MentorNode { get; set; }
    public bool PinToMentorNode { get; set; }
    public ArchivedDataProcessingBehavior? ArchivedDataProcessingBehavior { get; set; }
}
```

#### SubscriptionCreationOptions

```csharp
public class SubscriptionCreationOptions
{
    public string Name { get; set; }
    public string Query { get; set; }
    public string ChangeVector { get; set; }
    public virtual bool Disabled { get; set; }
    public string MentorNode { get; set; }
    public virtual bool PinToMentorNode { get; set; }
    public ArchivedDataProcessingBehavior? ArchivedDataProcessingBehavior { get; set; }
}
```

#### PredicateSubscriptionCreationOptions

```csharp
public sealed class PredicateSubscriptionCreationOptions
{
    public string Name { get; set; }
    public string ChangeVector { get; set; }
    public bool Disabled { get; set; }
    public string MentorNode { get; set; }
    public bool PinToMentorNode { get; set; }
    public ArchivedDataProcessingBehavior? ArchivedDataProcessingBehavior { get; set; }
}
```

#### SubscriptionUpdateOptions

```csharp
public class SubscriptionUpdateOptions : SubscriptionCreationOptions
{
    public long? Id { get; set; }
    public bool CreateNew { get; set; }
}
```

| Property | Type | Description |
| - | - | - |
| **\<T>** | `T` | The type whose collection the subscription draws its documents from. |
| **Name** | `string` | A user-defined name for the subscription. Must be unique within the database. |
| **Query** | `string` | An RQL query that defines the subscription.<br />See [Subscription query](#subscription-query). |
| **Filter** | `Expression<Func<T, bool>>` | A lambda expression defining the subscription's filter. Translated to a JavaScript function. |
| **Projection** | `Expression<Func<T, object>>` | A lambda expression defining the [projection](#projections) sent for each matching document. Translated to a JavaScript function.<br />The projection can create an anonymous object.<br />The projection can also create an object of a class or record you define, using an object initializer or a constructor call.<br />See [Projecting into your own class or record](#projecting-into-your-own-class-or-record). |
| **Includes** | `Action<ISubscriptionIncludeBuilder<T>>` | An action defining the subscription's include clauses. Included documents, counters, and time series are part of the batch the subscription sends. The [include methods](#include-builder) can be chained. |
| **ChangeVector** | `string` | A change vector marking where the subscription starts processing. See [Starting point](#starting-point). |
| **Disabled** | `bool` | `true` creates the subscription disabled, so the subscription does not accept worker connections until you [enable it](https://docs.ravendb.net/7.2/data-subscriptions/maintenance-operations.md#enabling-and-disabling-a-subscription).<br />Default: `false`. |
| **MentorNode** | `string` | The tag of the node you want to handle the subscription. Useful when you prefer a specific server for its hardware, its proximity to clients, or other reasons. |
| **PinToMentorNode** | `bool` | `true` keeps the subscription on the node set in `MentorNode`, even while that node is down.<br />See [Responsible node](#responsible-node). Default: `false`. |
| **ArchivedDataProcessingBehavior** | `ArchivedDataProcessingBehavior?` | The subscription's handling of archived documents.<br />See [Archived documents](#archived-documents). |

The `SubscriptionUpdateOptions` class adds two properties to the creation options:

| Property | Type | Description |
| - | - | - |
| **Id** | `long?` | The ID the server assigned the subscription at creation. Retrieve it from the subscription's state. When updating, the `Id` can be used instead of the `Name` and takes precedence over the `Name`. |
| **CreateNew** | `bool` | What to do when the target subscription does not exist. `true` creates a new subscription from the provided options; `false` throws. Default: `false`. |

### Include builder

The function you assign to the `Includes` property of a [SubscriptionCreationOptions\<T>](#classes) object
receives an `ISubscriptionIncludeBuilder<T>` object, whose methods add includes to the subscription.  
Calls to the builder's methods can be chained.  
See, for instance, the chained calls in [Example: Including counters](#example-including-counters).

---

#### Include builder: documents

```csharp
// Include the documents whose IDs are held by the field at the given path
ISubscriptionIncludeBuilder<T> IncludeDocuments(string path);
ISubscriptionIncludeBuilder<T> IncludeDocuments(Expression<Func<T, string>> path);
ISubscriptionIncludeBuilder<T> IncludeDocuments(Expression<Func<T, IEnumerable<string>>> path);

// The same, for a field holding IDs without their collection prefix
ISubscriptionIncludeBuilder<T> IncludeDocuments<TInclude>(Expression<Func<T, string>> path);
ISubscriptionIncludeBuilder<T> IncludeDocuments<TInclude>(Expression<Func<T, IEnumerable<string>>> path);
```

| Parameter | Type | Description |
| - | - | - |
| **path** | `string` | The path to the field holding the ID or IDs of the documents to include, e.g., `"Employee"` or `"Lines[].Product"`. |
| **path** | `Expression<Func<T, string>>` | An expression selecting the field holding the ID of the document to include, e.g., `x => x.Employee`. |
| **path** | `Expression<Func<T, IEnumerable<string>>>` | An expression selecting the IDs of the documents to include, e.g., `x => x.Lines.Select(y => y.Product)`. |
| **\<TInclude>** | `TInclude` | The type of the included documents.<br />Use it when the field holds IDs without their collection prefix: the ID prefix of `TInclude` (e.g., `products/`) is added to each ID. |

See [Example: Including documents](#example-including-documents).

---

#### Include builder: counters

```csharp
// Include a single counter
ISubscriptionIncludeBuilder<T> IncludeCounter(string name);

// Include multiple counters
ISubscriptionIncludeBuilder<T> IncludeCounters(string[] names);

// Include ALL counters from ALL documents that match the subscription criteria
ISubscriptionIncludeBuilder<T> IncludeAllCounters();
```

| Parameter | Type | Description |
| - | - | - |
| **name** | `string` | The name of a counter. The subscription includes every counter with this name in the documents it retrieves. |
| **names** | `string[]` | An array of counter names. |

See [Example: Including counters](#example-including-counters).

---

#### Include builder: time series

```csharp
// Include entries of a named time series, by a time range or by a number of entries
ISubscriptionIncludeBuilder<T> IncludeTimeSeries(string name, TimeSeriesRangeType type, TimeValue time);
ISubscriptionIncludeBuilder<T> IncludeTimeSeries(string name, TimeSeriesRangeType type, int count);

// The same, for several named time series
ISubscriptionIncludeBuilder<T> IncludeTimeSeries(string[] names, TimeSeriesRangeType type, TimeValue time);
ISubscriptionIncludeBuilder<T> IncludeTimeSeries(string[] names, TimeSeriesRangeType type, int count);

// Include all time series
ISubscriptionIncludeBuilder<T> IncludeAllTimeSeries(TimeSeriesRangeType type, TimeValue time);
ISubscriptionIncludeBuilder<T> IncludeAllTimeSeries(TimeSeriesRangeType type, int count);
```

| Parameter | Type | Description |
| - | - | - |
| **name** / **names** | `string` / `string[]` | The time series to include. |
| **type** | `TimeSeriesRangeType` | The range type, which must be `Last`. |
| **time** | `TimeValue` | A time range to include, for example the last 7 days. |
| **count** | `int` | A number of entries to include, counted from the most recent. |

See [Example: Including time series](#example-including-time-series).
