Table of Contents

Class Database

Namespace
Microsoft.Azure.Cosmos
Assembly
Microsoft.Azure.Cosmos.Client.dll

Operations for reading or deleting an existing database.

See Client for creating new databases, and reading/querying all databases; use client.Databases.

public abstract class Database
Inheritance
Database
Inherited Members
Extension Methods

Remarks

Note: all these operations make calls against a fixed budget. You should design your system such that these calls scale sub-linearly with your application. For instance, do not call database.ReadAsync() before every single container.ReadItemAsync() call to ensure the database exists; do this once on application start up.

Constructors

Database()

protected Database()

Properties

Client

The parent Cosmos client instance related the database instance

public abstract CosmosClient Client { get; }

Property Value

CosmosClient

Id

The Id of the Cosmos database

public abstract string Id { get; }

Property Value

string

Methods

CreateClientEncryptionKeyAsync(ClientEncryptionKeyProperties, RequestOptions, CancellationToken)

Saves the client encryption key as an asynchronous operation in the Azure Cosmos service. This method is not meant to be invoked directly. Please see https://aka.ms/CosmosClientEncryption in order to use client-side encryption.

public abstract Task<ClientEncryptionKeyResponse> CreateClientEncryptionKeyAsync(ClientEncryptionKeyProperties clientEncryptionKeyProperties, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

clientEncryptionKeyProperties ClientEncryptionKeyProperties

Client encryption key properties.

requestOptions RequestOptions

(Optional) The options for the request.

cancellationToken CancellationToken

(Optional) Token representing request cancellation.

Returns

Task<ClientEncryptionKeyResponse>

An awaitable response which wraps a ClientEncryptionKeyProperties containing the read resource record.

CreateContainerAsync(ContainerProperties, ThroughputProperties, RequestOptions, CancellationToken)

Creates a container as an asynchronous operation in the Azure Cosmos service.

public abstract Task<ContainerResponse> CreateContainerAsync(ContainerProperties containerProperties, ThroughputProperties throughputProperties, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

containerProperties ContainerProperties

The ContainerProperties object.

throughputProperties ThroughputProperties

(Optional) The throughput provisioned for a container in measurement of Requests Units per second in the Azure Cosmos DB service.

requestOptions RequestOptions

(Optional) The options for the request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ContainerResponse>

A Task containing a ContainerResponse which wraps a ContainerProperties containing the read resource record.

Examples

ContainerProperties containerProperties = new ContainerProperties()
{
    Id = Guid.NewGuid().ToString(),
    PartitionKeyPath = "/pk",
    IndexingPolicy = new IndexingPolicy()
   {
        Automatic = false,
        IndexingMode = IndexingMode.Lazy,
   }
};

ContainerResponse response = await this.cosmosDatabase.CreateContainerAsync(
    containerProperties,
    ThroughputProperties.CreateAutoscaleThroughput(10000));
See Also

CreateContainerAsync(ContainerProperties, int?, RequestOptions, CancellationToken)

Creates a container as an asynchronous operation in the Azure Cosmos service.

public abstract Task<ContainerResponse> CreateContainerAsync(ContainerProperties containerProperties, int? throughput = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

containerProperties ContainerProperties

The ContainerProperties object.

throughput int?

(Optional) The throughput provisioned for a container in measurement of Requests Units per second in the Azure Cosmos DB service.

requestOptions RequestOptions

(Optional) The options for the request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ContainerResponse>

A Task containing a ContainerResponse which wraps a ContainerProperties containing the read resource record.

Examples

ContainerProperties containerProperties = new ContainerProperties()
{
    Id = Guid.NewGuid().ToString(),
    PartitionKeyPath = "/pk",
    IndexingPolicy = new IndexingPolicy()
   {
        Automatic = false,
        IndexingMode = IndexingMode.Lazy,
   }
};

ContainerResponse response = await this.cosmosDatabase.CreateContainerAsync(containerProperties);
See Also

CreateContainerAsync(string, string, int?, RequestOptions, CancellationToken)

Creates a container as an asynchronous operation in the Azure Cosmos service.

public abstract Task<ContainerResponse> CreateContainerAsync(string id, string partitionKeyPath, int? throughput = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

id string

The Cosmos container id

partitionKeyPath string

The path to the partition key. Example: /location

throughput int?

(Optional) The throughput provisioned for a container in measurement of Requests Units per second in the Azure Cosmos DB service.

requestOptions RequestOptions

(Optional) The options for the request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ContainerResponse>

A Task containing a ContainerResponse which wraps a ContainerProperties containing the read resource record.

Examples

ContainerResponse response = await this.cosmosDatabase.CreateContainerAsync(Guid.NewGuid().ToString(), "/pk");
See Also

CreateContainerIfNotExistsAsync(ContainerProperties, ThroughputProperties, RequestOptions, CancellationToken)

Check if a container exists, and if it doesn't, create it. Only the container id is used to verify if there is an existing container. Other container properties such as throughput are not validated and can be different then the passed properties.

public abstract Task<ContainerResponse> CreateContainerIfNotExistsAsync(ContainerProperties containerProperties, ThroughputProperties throughputProperties, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

containerProperties ContainerProperties

The ContainerProperties object.

throughputProperties ThroughputProperties

(Optional) The throughput provisioned for a container in measurement of Requests Units per second in the Azure Cosmos DB service.

requestOptions RequestOptions

(Optional) The options for the request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ContainerResponse>

A Task containing a ContainerResponse which wraps a ContainerProperties containing the read resource record.

StatusCodeCommon success StatusCodes for the CreateDatabaseIfNotExistsAsync operation
201Created - New database is created.
200OK - This means the database already exists.

Examples

ContainerProperties containerProperties = new ContainerProperties()
{
    Id = Guid.NewGuid().ToString(),
    PartitionKeyPath = "/pk",
    IndexingPolicy = new IndexingPolicy()
   {
        Automatic = false,
        IndexingMode = IndexingMode.Lazy,
   }
};

ContainerResponse response = await this.cosmosDatabase.CreateContainerIfNotExistsAsync(
     containerProperties,
     ThroughputProperties.CreateAutoscaleThroughput(5000));
See Also

CreateContainerIfNotExistsAsync(ContainerProperties, int?, RequestOptions, CancellationToken)

Check if a container exists, and if it doesn't, create it. Only the container id is used to verify if there is an existing container. Other container properties such as throughput are not validated and can be different then the passed properties.

public abstract Task<ContainerResponse> CreateContainerIfNotExistsAsync(ContainerProperties containerProperties, int? throughput = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

containerProperties ContainerProperties

The ContainerProperties object.

throughput int?

(Optional) The throughput provisioned for a container in measurement of Requests Units per second in the Azure Cosmos DB service.

requestOptions RequestOptions

(Optional) The options for the request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ContainerResponse>

A Task containing a ContainerResponse which wraps a ContainerProperties containing the read resource record.

StatusCodeCommon success StatusCodes for the CreateDatabaseIfNotExistsAsync operation
201Created - New database is created.
200OK - This means the database already exists.

Examples

ContainerProperties containerProperties = new ContainerProperties()
{
    Id = Guid.NewGuid().ToString(),
    PartitionKeyPath = "/pk",
    IndexingPolicy = new IndexingPolicy()
   {
        Automatic = false,
        IndexingMode = IndexingMode.Lazy,
   }
};

ContainerResponse response = await this.cosmosDatabase.CreateContainerIfNotExistsAsync(containerProperties);
See Also

CreateContainerIfNotExistsAsync(string, string, int?, RequestOptions, CancellationToken)

Check if a container exists, and if it doesn't, create it. This will make a read operation, and if the container is not found it will do a create operation.

public abstract Task<ContainerResponse> CreateContainerIfNotExistsAsync(string id, string partitionKeyPath, int? throughput = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

id string

The Cosmos container id

partitionKeyPath string

The path to the partition key. Example: /location

throughput int?

(Optional) The throughput provisioned for a container in measurement of Request Units per second in the Azure Cosmos DB service.

requestOptions RequestOptions

(Optional) The options for the request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ContainerResponse>

A Task containing a ContainerResponse which wraps a ContainerProperties containing the read resource record.

Examples

ContainerResponse response = await this.cosmosDatabase.CreateContainerIfNotExistsAsync(Guid.NewGuid().ToString(), "/pk");
See Also

CreateContainerStreamAsync(ContainerProperties, ThroughputProperties, RequestOptions, CancellationToken)

Creates a container as an asynchronous operation in the Azure Cosmos service.

public abstract Task<ResponseMessage> CreateContainerStreamAsync(ContainerProperties containerProperties, ThroughputProperties throughputProperties, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

containerProperties ContainerProperties

The ContainerProperties object.

throughputProperties ThroughputProperties

(Optional) The throughput provisioned for a container in measurement of Request Units per second in the Azure Cosmos DB service.

requestOptions RequestOptions

(Optional) The options for the container request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ResponseMessage>

A Task containing a ResponseMessage containing the created resource record.

Examples

Creates a container as an asynchronous operation in the Azure Cosmos service and return stream response.

ContainerProperties containerProperties = new ContainerProperties()
{
    Id = Guid.NewGuid().ToString(),
    PartitionKeyPath = "/pk",
};

using(ResponseMessage response = await this.cosmosDatabase.CreateContainerStreamAsync(
    containerProperties,
    ThroughputProperties.CreateAutoscaleThroughput(10000)))
{
}
See Also

CreateContainerStreamAsync(ContainerProperties, int?, RequestOptions, CancellationToken)

Creates a container as an asynchronous operation in the Azure Cosmos service.

public abstract Task<ResponseMessage> CreateContainerStreamAsync(ContainerProperties containerProperties, int? throughput = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

containerProperties ContainerProperties

The ContainerProperties object.

throughput int?

(Optional) The throughput provisioned for a container in measurement of Request Units per second in the Azure Cosmos DB service.

requestOptions RequestOptions

(Optional) The options for the container request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ResponseMessage>

A Task containing a ResponseMessage containing the created resource record.

Examples

Creates a container as an asynchronous operation in the Azure Cosmos service and return stream response.

ContainerProperties containerProperties = new ContainerProperties()
{
    Id = Guid.NewGuid().ToString(),
    PartitionKeyPath = "/pk",
};

using(ResponseMessage response = await this.cosmosDatabase.CreateContainerStreamAsync(containerProperties))
{
}
See Also

CreateUserAsync(string, RequestOptions, CancellationToken)

Creates a user as an asynchronous operation in the Azure Cosmos service.

public abstract Task<UserResponse> CreateUserAsync(string id, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

id string

The Cosmos user id

requestOptions RequestOptions

(Optional) The options for the user request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<UserResponse>

A Task containing a UserResponse which wraps a UserProperties containing the read resource record.

Examples

UserResponse response = await this.cosmosDatabase.CreateUserAsync(Guid.NewGuid().ToString());

DefineContainer(string, string)

Creates a containerBuilder.

public abstract ContainerBuilder DefineContainer(string name, string partitionKeyPath)

Parameters

name string

Azure Cosmos container name to create.

partitionKeyPath string

The path to the partition key. Example: /partitionKey

Returns

ContainerBuilder

A fluent definition of an Azure Cosmos container.

Examples

CosmosContainerResponse container = await this.cosmosDatabase.DefineContainer("TestContainer", "/partitionKey")
    .UniqueKey()
        .Path("/path1")
        .Path("/path2")
        .Attach()
    .IndexingPolicy()
        .IndexingMode(IndexingMode.Consistent)
        .AutomaticIndexing(false)
        .IncludedPaths()
            .Path("/includepath1")
            .Path("/includepath2")
            .Attach()
        .ExcludedPaths()
            .Path("/excludepath1")
            .Path("/excludepath2")
            .Attach()
        .CompositeIndex()
            .Path("/root/leaf1")
            .Path("/root/leaf2", CompositePathSortOrder.Descending)
            .Attach()
        .CompositeIndex()
            .Path("/root/leaf3")
            .Path("/root/leaf4")
            .Attach()
        .Attach()
    .CreateAsync(5000 /* throughput /*);

DeleteAsync(RequestOptions, CancellationToken)

Delete a Database from the Azure Cosmos DB service as an asynchronous operation.

public abstract Task<DatabaseResponse> DeleteAsync(RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

requestOptions RequestOptions

(Optional) The options for the request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<DatabaseResponse>

A Task containing a DatabaseResponse which will contain information about the request issued.

Examples

// Delete a Cosmos database
Database database = cosmosClient.GetDatabase("myDbId");
DatabaseResponse response = await database.DeleteAsync();

DeleteStreamAsync(RequestOptions, CancellationToken)

Delete a DatabaseProperties from the Azure Cosmos DB service as an asynchronous operation.

public abstract Task<ResponseMessage> DeleteStreamAsync(RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

requestOptions RequestOptions

(Optional) The options for the request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ResponseMessage>

A Task containing a ResponseMessage which will contain information about the request issued.

Examples

// Delete a Database resource where database_id is the ID property of the Database resource you wish to delete.
Database database = this.cosmosClient.GetDatabase(database_id);
await database.DeleteStreamAsync();

GetClientEncryptionKey(string)

Returns a reference to a client encryption key object. This method is not meant to be invoked directly. Please see https://aka.ms/CosmosClientEncryption in order to use client-side encryption.

public abstract ClientEncryptionKey GetClientEncryptionKey(string id)

Parameters

id string

Unique identifier for the client encryption key.

Returns

ClientEncryptionKey

Client encryption key reference.

Remarks

The reference returned doesn't guarantee existence of the client encryption key. Please ensure it already exists or is created through CreateClientEncryptionKeyAsync(ClientEncryptionKeyProperties, RequestOptions, CancellationToken).

GetClientEncryptionKeyQueryIterator(QueryDefinition, string, QueryRequestOptions)

Returns an iterator that can be iterated to get properties of client encryption keys. This method is not meant to be invoked directly. Please see https://aka.ms/CosmosClientEncryption in order to use client-side encryption.

public abstract FeedIterator<ClientEncryptionKeyProperties> GetClientEncryptionKeyQueryIterator(QueryDefinition queryDefinition, string continuationToken = null, QueryRequestOptions requestOptions = null)

Parameters

queryDefinition QueryDefinition

The Cosmos SQL query definition.

continuationToken string

(Optional) The continuation token in the Azure Cosmos DB service.

requestOptions QueryRequestOptions

(Optional) The options for the request. Set MaxItemCount to restrict the number of results returned.

Returns

FeedIterator<ClientEncryptionKeyProperties>

An iterator over client encryption keys.

Remarks

ReadAsync(RequestOptions, CancellationToken) is recommended for single client encryption key look-up.

GetContainer(string)

Returns a reference to a container object.

public abstract Container GetContainer(string id)

Parameters

id string

The Cosmos container id.

Returns

Container

Cosmos container reference

Examples

Database db = this.cosmosClient.GetDatabase("myDatabaseId");
Container container = db.GetContainer("testcontainer");

Remarks

Returns a Container reference. Reference doesn't guarantee existence. Please ensure container already exists or is created through a create operation.

GetContainerQueryIterator<T>(QueryDefinition, string, QueryRequestOptions)

This method creates a query for containers under an database using a SQL statement with parameterized values. It returns a FeedIterator. For more information on preparing SQL statements with parameterized values, please see QueryDefinition overload.

public abstract FeedIterator<T> GetContainerQueryIterator<T>(QueryDefinition queryDefinition, string continuationToken = null, QueryRequestOptions requestOptions = null)

Parameters

queryDefinition QueryDefinition

The Cosmos SQL query definition.

continuationToken string

(Optional) The continuation token in the Azure Cosmos DB service.

requestOptions QueryRequestOptions

(Optional) The options for the item query request.

Returns

FeedIterator<T>

An iterator to go through the containers

Type Parameters

T

Examples

This create the type feed iterator for containers with queryDefinition as input.

QueryDefinition queryDefinition = new QueryDefinition("SELECT * FROM c where c.status like @status");
    .WithParameter("@status", "start%");
using (FeedIterator<ContainerProperties> feedIterator = this.cosmosDatabase.GetContainerQueryIterator<ContainerProperties>(queryDefinition))
{
    while (feedIterator.HasMoreResults)
    {
        FeedResponse<ContainerProperties> response = await feedIterator.ReadNextAsync();
        foreach (var container in response)
        {
            Console.WriteLine(container);
        }
    }
}

Remarks

GetContainerQueryIterator<T>(string, string, QueryRequestOptions)

This method creates a query for containers under an database using a SQL statement. It returns a FeedIterator.

public abstract FeedIterator<T> GetContainerQueryIterator<T>(string queryText = null, string continuationToken = null, QueryRequestOptions requestOptions = null)

Parameters

queryText string

The Cosmos SQL query text.

continuationToken string

(Optional) The continuation token in the Azure Cosmos DB service.

requestOptions QueryRequestOptions

(Optional) The options for the item query request.

Returns

FeedIterator<T>

An iterator to go through the containers

Type Parameters

T

Examples

  1. This create the type feed iterator for containers with queryText as input,
string queryText = "SELECT * FROM c where c.status like 'start%'";
using (FeedIterator<ContainerProperties> feedIterator = this.cosmosDatabase.GetContainerQueryIterator<ContainerProperties>(queryText))
{
    while (feedIterator.HasMoreResults)
    {
        FeedResponse<ContainerProperties> response = await feedIterator.ReadNextAsync();
        foreach (var container in response)
        {
            Console.WriteLine(container);
        }
    }
}
  1. This create the type feed iterator for containers without queryText, retrieving all containers.
using (FeedIterator<ContainerProperties> feedIterator = this.cosmosDatabase.GetContainerQueryIterator<ContainerProperties>())
{
    while (feedIterator.HasMoreResults)
    {
        FeedResponse<ContainerProperties> response = await feedIterator.ReadNextAsync();
        foreach (var container in response)
        {
           Console.WriteLine(container);
        }
    }
}

Remarks

GetContainerQueryStreamIterator(QueryDefinition, string, QueryRequestOptions)

This method creates a query for containers under an database using a SQL statement with parameterized values. It returns a FeedIterator. For more information on preparing SQL statements with parameterized values, please see QueryDefinition overload.

public abstract FeedIterator GetContainerQueryStreamIterator(QueryDefinition queryDefinition, string continuationToken = null, QueryRequestOptions requestOptions = null)

Parameters

queryDefinition QueryDefinition

The Cosmos SQL query definition.

continuationToken string

The continuation token in the Azure Cosmos DB service.

requestOptions QueryRequestOptions

(Optional) The options for the container request.

Returns

FeedIterator

An iterator to go through the containers

Examples

This create the stream feed iterator for containers with queryDefinition as input.

string queryText = "SELECT c.id FROM c where c.status like 'start%'";
QueryDefinition queryDefinition = new QueryDefinition(queryText);
using (FeedIterator feedIterator = this.cosmosDatabase.GetContainerQueryStreamIterator(queryDefinition))
{
    while (feedIterator.HasMoreResults)
    {
        using (ResponseMessage response = await feedIterator.ReadNextAsync())
        {
            response.EnsureSuccessStatusCode();
            using (StreamReader sr = new StreamReader(response.Content))
            using (JsonTextReader jtr = new JsonTextReader(sr))
            {
                // The stream content contains the following JSON structure
                // {"_rid":"FwsdAA==","DocumentCollections":[{"id":"container1"},{"id":"container2"}],"_count":2}
                JObject result = JObject.Load(jtr);
            }
        }
    }
}

This creates feed iterator to get a list of all the container ids

using (FeedIterator feedIterator = this.cosmosDatabase.GetContainerQueryStreamIterator(
      new QueryDefinition("select value c.id From c ")))
  {
      while (feedIterator.HasMoreResults)
      {
          using (ResponseMessage response = await feedIterator.ReadNextAsync())
          {
               response.EnsureSuccessStatusCode();
               using (StreamReader streamReader = new StreamReader(response.Content))
               using (JsonTextReader jsonTextReader = new JsonTextReader(streamReader))
               {
                    // The stream content contains the following JSON structure
                    // {"_rid":"7p8wAA==","DocumentCollections":["container1","container2"],"_count":2}
                    JObject jObject = await JObject.LoadAsync(jsonTextReader);
                }
        }
    }
}

Remarks

GetContainerQueryStreamIterator(string, string, QueryRequestOptions)

This method creates a query for containers under an database using a SQL statement. It returns a FeedIterator.

public abstract FeedIterator GetContainerQueryStreamIterator(string queryText = null, string continuationToken = null, QueryRequestOptions requestOptions = null)

Parameters

queryText string

The Cosmos SQL query text.

continuationToken string

The continuation token in the Azure Cosmos DB service.

requestOptions QueryRequestOptions

(Optional) The options for the container request.

Returns

FeedIterator

An iterator to go through the containers

Examples

This create the stream feed iterator for containers with queryDefinition as input.

using (FeedIterator feedIterator = this.cosmosDatabase.GetContainerQueryStreamIterator(
    "SELECT c.id FROM c where c.status like 'start%'"))
{
    while (feedIterator.HasMoreResults)
    {
        using (ResponseMessage response = await feedIterator.ReadNextAsync())
        {
            response.EnsureSuccessStatusCode();
            using (StreamReader sr = new StreamReader(response.Content))
            using (JsonTextReader jtr = new JsonTextReader(sr))
            {
                // The stream content contains the following JSON structure
                // {"_rid":"FwsdAA==","DocumentCollections":[{"id":"container1"},{"id":"container2"}],"_count":2}
                JObject result = JObject.Load(jtr);
            }
        }
    }
}

This creates feed iterator to get a list of all the container ids

using (FeedIterator feedIterator = this.cosmosDatabase.GetContainerQueryStreamIterator(
      "select value c.id From c "))
  {
      while (feedIterator.HasMoreResults)
      {
          using (ResponseMessage response = await feedIterator.ReadNextAsync())
          {
               response.EnsureSuccessStatusCode();
               using (StreamReader streamReader = new StreamReader(response.Content))
               using (JsonTextReader jsonTextReader = new JsonTextReader(streamReader))
               {
                    // The stream content contains the following JSON structure
                    // {"_rid":"7p8wAA==","DocumentCollections":["container1","container2"],"_count":2}
                    JObject jObject = await JObject.LoadAsync(jsonTextReader);
                }
        }
    }
}

Remarks

GetUser(string)

Returns a reference to a user object.

public abstract User GetUser(string id)

Parameters

id string

The Cosmos user id.

Returns

User

Cosmos user reference

Examples

Database db = this.cosmosClient.GetDatabase("myDatabaseId");
User user = await db.GetUser("userId");
UserResponse response = await user.ReadAsync();

Remarks

Returns a User reference. Reference doesn't guarantee existence. Please ensure user already exists or is created through a create operation.

GetUserQueryIterator<T>(QueryDefinition, string, QueryRequestOptions)

This method creates a query for users under an database using a SQL statement with parameterized values. It returns a FeedIterator. For more information on preparing SQL statements with parameterized values, please see QueryDefinition overload.

public abstract FeedIterator<T> GetUserQueryIterator<T>(QueryDefinition queryDefinition, string continuationToken = null, QueryRequestOptions requestOptions = null)

Parameters

queryDefinition QueryDefinition

The Cosmos SQL query definition.

continuationToken string

(Optional) The continuation token in the Azure Cosmos DB service.

requestOptions QueryRequestOptions

(Optional) The options for the user query request.

Returns

FeedIterator<T>

An iterator to go through the users

Type Parameters

T

Examples

This create the type feed iterator for users with queryDefinition as input.

QueryDefinition queryDefinition = new QueryDefinition("SELECT * FROM c where c.status like @status")
    .WithParameter("@status", "start%");
using (FeedIterator<UserProperties> resultSet = this.cosmosDatabase.GetUserQueryIterator<UserProperties>(queryDefinition))
{
    while (feedIterator.HasMoreResults)
    {
        foreach (UserProperties properties in await feedIterator.ReadNextAsync())
        {
            Console.WriteLine(properties.Id);
        }
    }
}

GetUserQueryIterator<T>(string, string, QueryRequestOptions)

This method creates a query for users under an database using a SQL statement. It returns a FeedIterator.

public abstract FeedIterator<T> GetUserQueryIterator<T>(string queryText = null, string continuationToken = null, QueryRequestOptions requestOptions = null)

Parameters

queryText string

The Cosmos SQL query text.

continuationToken string

(Optional) The continuation token in the Azure Cosmos DB service.

requestOptions QueryRequestOptions

(Optional) The options for the user query request.

Returns

FeedIterator<T>

An iterator to go through the users

Type Parameters

T

Examples

  1. This create the type feed iterator for users with queryText as input,
string queryText = "SELECT * FROM c where c.status like 'start%'";
using (FeedIterator<UserProperties> HasMoreResults = this.cosmosDatabase.GetUserQueryIterator<UserProperties>(queryText))
{
    while (feedIterator.HasMoreResults)
    {
        FeedResponse<UserProperties> response = await feedIterator.ReadNextAsync();
        foreach (var user in response)
        {
            Console.WriteLine(user);
        }
    }
}
  1. This create the type feed iterator for users without queryText, retrieving all users.
using (FeedIterator<UserProperties> feedIterator = this.cosmosDatabase.GetUserQueryIterator<UserProperties>())
{
    while (feedIterator.HasMoreResults)
    {
        FeedResponse<UserProperties> response = await feedIterator.ReadNextAsync();
        foreach (var user in response)
        {
            Console.WriteLine(user);
        }
    }
}

ReadAsync(RequestOptions, CancellationToken)

Reads a DatabaseResponse from the Azure Cosmos service as an asynchronous operation.

public abstract Task<DatabaseResponse> ReadAsync(RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

requestOptions RequestOptions

(Optional) The options for the request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<DatabaseResponse>

A Task containing a DatabaseResponse which wraps a DatabaseProperties containing the read resource record.

Examples

// Reads a Database resource where database_id is the ID property of the Database resource you wish to read.
Database database = this.cosmosClient.GetDatabase(database_id);
DatabaseResponse response = await database.ReadAsync();

Remarks

Resource contains the DatabaseProperties that include the resource information.

ReadStreamAsync(RequestOptions, CancellationToken)

Reads a DatabaseProperties from the Azure Cosmos service as an asynchronous operation.

public abstract Task<ResponseMessage> ReadStreamAsync(RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

requestOptions RequestOptions

(Optional) The options for the request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ResponseMessage>

A Task containing a ResponseMessage containing the read resource record.

Examples

// Reads a Database resource where database_id is the ID property of the Database resource you wish to read.
Database database = this.cosmosClient.GetDatabase(database_id);
ResponseMessage response = await database.ReadContainerStreamAsync();

ReadThroughputAsync(RequestOptions, CancellationToken)

Gets database throughput in measurement of request units per second in the Azure Cosmos service.

public abstract Task<ThroughputResponse> ReadThroughputAsync(RequestOptions requestOptions, CancellationToken cancellationToken = default)

Parameters

requestOptions RequestOptions

The options for the throughput request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ThroughputResponse>

The throughput response.

Examples

The following example shows how to get the throughput

 RequestOptions requestOptions = new RequestOptions();
ThroughputProperties throughputProperties = await database.ReadThroughputAsync(requestOptions);
Console.WriteLine($"Throughput: {throughputProperties?.Throughput}");

The following example shows how to get throughput, MinThroughput and is replace in progress

RequestOptions requestOptions = new RequestOptions();
ThroughputResponse response = await database.ReadThroughputAsync(requestOptions);
Console.WriteLine($"Throughput: {response.Resource?.Throughput}");
Console.WriteLine($"MinThroughput: {response.MinThroughput}");
Console.WriteLine($"IsReplacePending: {response.IsReplacePending}");

Exceptions

CosmosException

This exception can encapsulate many different types of errors. To determine the specific error always look at the StatusCode property. Some common codes you may get when reading a client encryption key are:

StatusCodeReason for exception
404 NotFound - This means the database does not exist or has no throughput assigned.
See Also

ReadThroughputAsync(CancellationToken)

Gets database throughput in measurement of request units per second in the Azure Cosmos service.

public abstract Task<int?> ReadThroughputAsync(CancellationToken cancellationToken = default)

Parameters

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<int?>

Provisioned throughput in request units per second

Examples

The following example shows how to get database throughput.

int? throughput = await database.ReadThroughputAsync();

Remarks

Null value indicates a database with no throughput provisioned.

See Also

ReplaceThroughputAsync(ThroughputProperties, RequestOptions, CancellationToken)

Sets throughput provisioned for a database in measurement of request units per second in the Azure Cosmos service.

public abstract Task<ThroughputResponse> ReplaceThroughputAsync(ThroughputProperties throughputProperties, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

throughputProperties ThroughputProperties

The Cosmos database throughput expressed in Request Units per second.

requestOptions RequestOptions

(Optional) The options for the throughput request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ThroughputResponse>

The throughput response.

Examples

The following example shows how to replace the manual throughput.

ThroughputResponse throughput = await this.cosmosDatabase.ReplaceThroughputAsync(
    ThroughputProperties.CreateManualThroughput(10000));

The following example shows how to replace the autoscale provisioned throughput.

ThroughputResponse throughput = await this.cosmosDatabase.ReplaceThroughputAsync(
    ThroughputProperties.CreateAutoscaleThroughput(10000));

Remarks

ReplaceThroughputAsync(int, RequestOptions, CancellationToken)

Sets throughput provisioned for a database in measurement of request units per second in the Azure Cosmos service.

public abstract Task<ThroughputResponse> ReplaceThroughputAsync(int throughput, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

throughput int

The Cosmos database throughput expressed in Request Units per second.

requestOptions RequestOptions

(Optional) The options for the throughput request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ThroughputResponse>

The throughput response.

Examples

The following example shows how to get the throughput.

ThroughputResponse throughput = await this.cosmosDatabase.ReplaceThroughputAsync(10000);

Remarks

UpsertUserAsync(string, RequestOptions, CancellationToken)

Upserts a user as an asynchronous operation in the Azure Cosmos service.

public abstract Task<UserResponse> UpsertUserAsync(string id, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

id string

The Cosmos user id.

requestOptions RequestOptions

(Optional) The options for the user request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<UserResponse>

A Task containing a UserResponse which wraps a UserProperties containing the read resource record.

Examples

UserResponse response = await this.cosmosDatabase.UpsertUserAsync(Guid.NewGuid().ToString());