---
title: "Include Compare Exchange Values"
url: "https://docs.ravendb.net/6.2/client-api/operations/compare-exchange/include-compare-exchange"
version: "6.2"
language: "nodejs"
---

# Include Compare Exchange Values

> Client language: Node.js. Also available for [C#](https://docs.ravendb.net/6.2/client-api/operations/compare-exchange/include-compare-exchange.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**
>
> - Compare-Exchange items can be included when [loading entities](https://docs.ravendb.net/6.2/client-api/session/loading-entities.nodejs.md)
>   and when making [queries](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-query.nodejs.md).
>
> - The Session [tracks](https://docs.ravendb.net/6.2/client-api/session/what-is-a-session-and-how-does-it-work.nodejs.md#tracking-changes)
>   the included Compare Exchange items which means their value can be accessed  
>   in that Session without making an additional call to the server.
>
> - In this page:
>   - [Sample data](#sample-data)
>   - [Include CmpXchg items when loading](#include-cmpxchg-items-when-loading)
>   - [Include CmpXchg items when querying](#include-cmpxchg-items-when-querying)
>   - [Syntax](#syntax)

## Sample data

- The examples in this article are based on the following **sample data**:

### Sample\_data

```javascript
{
  // Create some company documents:
  // ==============================

  const session = documentStore.openSession();

  const company1 = new Company();
  company1.id = "companies/1";
  company1.name = "Apple";
  company1.supplier = "suppliers/1";
  company1.workers = ["employees/1", "employees/2"];

  const company2 = new Company("companies/2", "Google", "suppliers/2", ["employees/3", "employees/4"]);
  const company3 = new Company("companies/3", "Microsoft", "suppliers/3", ["employees/6", "employees/5"]);

  await session.store(company1);
  await session.store(company2);
  await session.store(company3);

  await session.saveChanges();
}
{
  // Create some CmpXchg items:
  // ==========================

  // Open a session with cluster-wide mode so that we can call 'createCompareExchangeValue'
  const session = documentStore.openSession({
      transactionMode: "ClusterWide"
  });

  session.advanced.clusterTransaction.createCompareExchangeValue("employee/1", "content for employee 1 ..");
  session.advanced.clusterTransaction.createCompareExchangeValue("employee/2", "content for employee 2 ..");
  session.advanced.clusterTransaction.createCompareExchangeValue("employee/3", "content for employee 3 ..");

  session.advanced.clusterTransaction.createCompareExchangeValue("suppliers/1", "content for supplier 1 ..");
  session.advanced.clusterTransaction.createCompareExchangeValue("suppliers/2", "content for supplier 2 ..");
  session.advanced.clusterTransaction.createCompareExchangeValue("suppliers/3", "content for supplier 3 ..");
  
  await session.saveChanges();
}
```

### Company\_class

```javascript
class Company {
  constructor(
      id = null,
      name = "",
      supplier = "",
      workers = []

  ) {
      Object.assign(this, {
          id,
          name,
          supplier,
          workers
      });
  }
}
```

## Include CmpXchg items when loading

> **Note**
>
> **Include single item**:
>
> ```javascript
> // Open a session with cluster-wide mode to enable calling 'includeCompareExchangeValue'
> const session = documentStore.openSession({
>   transactionMode: "ClusterWide"
> });
>
> // Load a company document + include a CmpXchg item:
> // =================================================
>
> // Call 'includeCompareExchangeValue' within the 'load' options,
> // pass the PATH of the document property that contains the key of the CmpXchg item to include
> const company1 = await session.load("companies/1", {
>   documentType: Company,
>   // "supplier" is the document property that holds the cmpXchg key 
>   includes: i => i.includeCompareExchangeValue("supplier")
> });
>
> // Calling 'load' has triggered a server call
> const numberOfRequests = session.advanced.numberOfRequests;
> assert.equal(numberOfRequests, 1);
>
> // Access the included CmpXchg item:
> // =================================
>
> // Call 'getCompareExchangeValue' to access the content of the included CmpXchg item,
> // pass the cmpXchg item KEY. This will NOT trigger another server call.
> const item = await session.advanced.clusterTransaction
>   .getCompareExchangeValue(company1.supplier);
>
> // You can assert that no further server calls were made
> assert.equal(session.advanced.numberOfRequests, numberOfRequests);
>
> // The cmpXchg item value is available
> const value = item.value;
> ```

> **Note**
>
> **Include multiple items**:
>
> ```javascript
> const session = documentStore.openSession({
>   transactionMode: "ClusterWide"
> });
>
> // Load a company document + include multiple CmpXchg items:
> // =========================================================
>
> // Call 'includeCompareExchangeValue' within the 'load' options,
> // pass the PATH of the document property that contains the list keys of the CmpXchg items to include
> const company1 = await session.load("companies/1", {
>   documentType: Company,
>   // "workers" is the document property that holds the list of keys 
>   includes: i => i.includeCompareExchangeValue("workers")
> });
>
> const numberOfRequests = session.advanced.numberOfRequests;
> assert.equal(numberOfRequests, 1);
>
> // Access the included CmpXchg items:
> // ==================================
>
> // Call 'getCompareExchangeValues' to access the content of the included CmpXchg items, 
> // pass the list of KEYS. This will NOT trigger another server call.
> const items = await session.advanced.clusterTransaction
>   .getCompareExchangeValues(company1.workers);
>
> assert.equal(session.advanced.numberOfRequests, numberOfRequests);
>
> // The value of each item is available
> const value1 = items["employees/1"].value;
> const value2 = items["employees/2"].value;
> ```

## Include CmpXchg items when querying

> **Note**
>
> **dynamic query**:
>
> ### Query
>
> ```javascript
> // Open a session with cluster-wide mode to enable calling 'includeCompareExchangeValue'
> const session = documentStore.openSession({
>   transactionMode: "ClusterWide"
> });
>
> // Make a dynamic query + include CmpXchg items:
> // =============================================
>
> const companies = await session.query({ collection: "companies" })
>   // Call 'include' with 'includeCompareExchangeValue'
>   // pass the PATH of the document property that contains the key of the CmpXchg item to include  
>   .include(x => x.includeCompareExchangeValue("supplier"))
>   .all();
>
> // Making the query has triggered a server call
> const numberOfRequests = session.advanced.numberOfRequests;
> assert.equal(numberOfRequests, 1);
>
> // Access the included CmpXchg items:
> // ==================================
>
> const cmpXchgItems = [];
>
> for (let i = 0; i < companies.length; i++) {
>   // Call 'getCompareExchangeValues' to access the content of the included CmpXchg items,
>   // pass the KEY. This will NOT trigger another server call.
>   const item = await session.advanced.clusterTransaction
>       .getCompareExchangeValue(companies[i].supplier);
>
>   cmpXchgItems.push(item);
> }
>
> // You can assert that no further server calls were made
> assert.equal(session.advanced.numberOfRequests, numberOfRequests);
> ```
>
> ### RawQuery\_using\_RQL
>
> ```javascript
> // Open a session with cluster-wide mode to enable calling 'include cmpxchg'
> const session = documentStore.openSession({
>   transactionMode: "ClusterWide"
> });
>
> // Make a raw query + include CmpXchg items:
> // =========================================
>
> // In the provided RQL:
> // * Call 'include' with 'cmpxchg'
> // * Pass the PATH of the document property that contains the key of the CmpXchg item to include  
> const companies = await session.advanced
>   .rawQuery(`from companies as c
>              select c
>              include cmpxchg(c.supplier)`)
>   .all();
>
> const numberOfRequests = session.advanced.numberOfRequests;
> assert.equal(numberOfRequests, 1);
>
> // Access the included CmpXchg items:
> // ==================================
>
> const cmpXchgItems = [];
>
> for (let i = 0; i < companies.length; i++) {
>   // Call 'getCompareExchangeValues' to access the content of the included CmpXchg items, pass the KEY,
>   // this will NOT trigger another server call
>   const item = await session.advanced.clusterTransaction
>       .getCompareExchangeValue(companies[i].supplier);
>
>   cmpXchgItems.push(item);
> }
>
> assert.equal(session.advanced.numberOfRequests, numberOfRequests);
> ```
>
> ### RawQuery\_using\_JS\_function
>
> ```javascript
> // Open a session with cluster-wide mode to enable calling 'includes.cmpxchg'
> const session = documentStore.openSession({
>   transactionMode: "ClusterWide"
> });
>
> // Make a raw query + include CmpXchg items using Javascript method:
> // =================================================================
>
> // In the provided RQL:
> // * Call 'includes.cmpxchg'
> // * Pass the PATH of the document property that contains the key of the CmpXchg item to include  
> const companies = await session.advanced
>   .rawQuery(`declare function includeCmpXchg(company) {
>                 includes.cmpxchg(company.supplier);
>                 return company;
>            }
>            
>           from companies as c
>           select includeCmpXchg(c)`)
>   .all();
>
> const numberOfRequests = session.advanced.numberOfRequests;
> assert.equal(numberOfRequests, 1);
>
> // Access the included CmpXchg items:
> // ==================================
>
> const cmpXchgItems = [];
>
> for (let i = 0; i < companies.length; i++) {
>   // Call 'getCompareExchangeValues' to access the content of the included CmpXchg items,
>   // pass the KEY. This will NOT trigger another server call
>   const item = await session.advanced.clusterTransaction
>       .getCompareExchangeValue(companies[i].supplier);
>
>   cmpXchgItems.push(item);
> }
>
> assert.equal(session.advanced.numberOfRequests, numberOfRequests);
> ```

> **Note**
>
> **Index query**:
>
> ### Query
>
> ```javascript
> const session = documentStore.openSession({
>   transactionMode: "ClusterWide"
> });
>
> // Make an index query + include CmpXchg items:
> // ============================================
>
> // Call 'include' with 'includeCompareExchangeValue'
> // pass the PATH of the document property that contains the key of the CmpXchg item to include
> const companies = await session.query({ indexName: "Companies/ByName" })
>   .include(x => x.includeCompareExchangeValue("supplier"))
>   .all();
>
> const numberOfRequests = session.advanced.numberOfRequests;
> assert.equal(numberOfRequests, 1);
>
> // Access the included CmpXchg items:
> // ==================================
>
> const cmpXchgItems = [];
>
> for (let i = 0; i < companies.length; i++) {
>   // Call 'getCompareExchangeValues' to access the content of the included CmpXchg items,
>   // pass the KEY. This will NOT trigger another server call
>   const item = await session.advanced.clusterTransaction
>       .getCompareExchangeValue(companies[i].supplier);
>
>   cmpXchgItems.push(item);
> }
>
> assert.equal(session.advanced.numberOfRequests, numberOfRequests);
> ```
>
> ### Index
>
> ```javascript
> class Companies_ByName extends AbstractJavaScriptIndexCreationTask {
>   constructor() {
>       super();
>
>       this.map('companies', company => {
>           return {
>               name: company.name
>           };
>       });
>   }
> }
> ```
>
> ### RQL
>
> ```sql
> // RQL that can be used with a Raw Query:
> // ======================================
>
> from index "Companies/ByName"
> include cmpxchg("supplier")
>
> // Using JS method:
> // ================
>
> declare function includeCmpXchg(company) {
>   includes.cmpxchg(company.supplier);
>   return company;
> }
>
> from index "Companies/ByName" as c
> select includeCmpXchg(c)
> ```
>
> - Note:  
>   Similar to the above dynamic query example, you can query the index with a [raw query](https://docs.ravendb.net/6.2/indexes/querying/query-index.nodejs.md#sessionadvancedrawquery) using the provided RQL.

## Syntax

> **Note**
>
> **When loading entities or making queries**:
>
> - Use method `includeCompareExchangeValue()` to include compare-exchange items along with `session.load()` or with queries.
>
> ```javascript
> includeCompareExchangeValue(path);
> ```
>
> | Parameter | Type | Description |
> | - | - | - |
> | **path** | `string` | The path of the document property that contains the key (or list of keys) of the CmpXchg items to include |

> **Note**
>
> **When querying with RQL**:
>
> - Use the [include](https://docs.ravendb.net/6.2/client-api/session/querying/what-is-rql.md#include) keyword followed by `cmpxchg()` to include a compare-exchange item.
>
> ```sql
> include cmpxchg(key)
> ```

> **Note**
>
> **When using javascript functions within RQL**:
>
> - Use `includes.cmpxchg()` In [javascript functions](https://docs.ravendb.net/6.2/client-api/session/querying/what-is-rql.md#declare) within RQL queries.
>
> ```javascript
> includes.cmpxchg(key);
> ```
>
> | Parameter | Type | Description |
> | - | - | - |
> | **key** | `string` | The key of the compare exchange value you want to include, or a path to the key. |

## See also

- [Session Change Tracking](https://docs.ravendb.net/6.2/client-api/session/what-is-a-session-and-how-does-it-work.nodejs.md#tracking-changes)
- [How to: Handle Document Relationships](https://docs.ravendb.net/6.2/client-api/how-to/handle-document-relationships.nodejs.md)
- [Compare Exchange Overview](https://docs.ravendb.net/6.2/client-api/operations/compare-exchange/overview.md)
- [Indexing Compare Exchange Values](https://docs.ravendb.net/6.2/indexes/indexing-compare-exchange-values.nodejs.md)
