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:
- Keep container names between 3 and 63 characters long
- Container names can only contain lowercase letters, numbers, or the dash (-) character.
- Container names must start with a lowercase letter or number.
Once created, the URI for a container is in this format:
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 );
Database.CreateContainerAsync method will throw 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 );
Database.CreateContainerIfNotExistsAsync method will only create 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
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;
Now that you've create a container, use the next guide to create items.