Create a container in Azure Cosmos DB for NoSQL using .NET

APPLIES TO: NoSQL

Containers in Azure Cosmos DB store sets of items. Before you can create, query, or manage items, you must first create a container.

Name a container

In Azure Cosmos DB, a container is analogous to a table in a relational database. When you create a container, the container name forms a segment of the URI used to access the container resource and any child items.

Here are some quick rules when naming a container:

  • Container names must not be empty.
  • Container names can't be longer than 256 characters.

Once created, the URI for a container is in this format:

https://<cosmos-account-name>.documents.azure.cn/dbs/<database-name>/colls/<container-name>

Tip

For more information on container name limits, see service quotas and limits

Create a container

To create a container, call one of the following methods:

Create a container asynchronously

The following example creates a container asynchronously:

// New instance of Container class referencing the server-side container
Container container1 = await database.CreateContainerAsync(
    id: "products-1",
    partitionKeyPath: "/category",
    throughput: 400
);

The Database.CreateContainerAsync method throws an exception if a database with the same name already exists.

Create a container asynchronously if it doesn't already exist

The following example creates a container asynchronously only if it doesn't already exist on the account:

// New instance of Container class referencing the server-side container
Container container2 = await database.CreateContainerIfNotExistsAsync(
    id: "products-2",
    partitionKeyPath: "/category",
    throughput: 400
);

The Database.CreateContainerIfNotExistsAsync method only creates a new container if it doesn't already exist. This method is useful for avoiding errors if you run the same code multiple times.

Parsing the response

In all examples so far, the response from the asynchronous request was cast immediately to the Container type. You may want to parse metadata about the response including headers and the HTTP status code. The true return type for the Database.CreateContainerAsync and Database.CreateContainerIfNotExistsAsync methods is ContainerResponse.

The following example shows the Database.CreateContainerIfNotExistsAsync method returning a ContainerResponse. Once returned, you can parse response properties and then eventually get the underlying Container object:

// New instance of Container class referencing the server-side container
ContainerResponse response = await database.CreateContainerIfNotExistsAsync(
    id: "products-3",
    partitionKeyPath: "/category",
    throughput: 400
);
// Parse additional response properties
Container container3 = response.Container;

Next steps

Now that you've create a container, use the next guide to create items.