Create a container in Azure Cosmos DB for NoSQL using JavaScript
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.
Once created, the URI for a container is in this format:
https://<cosmos-account-name>.documents.azure.com/dbs/<database-name>/colls/<container-name>
Create a container
Get a Database object, then create a Container:
- createIfNotExists - Creates a container if it doesn't exist. If it does exist, return container.
- create - Creates a container. If it does exist, return error statusCode.
const containerName = 'myContainer';
// Possible results:
// Create then return container
// Return existing container
// Return error statusCode
const { statusCode, container } = await database.containers.createIfNotExists({ id: containerName });
// Possible results:
// Create then return container
// Return error statusCode, reason includes container already exists
const { statusCode, container} = await database.containers.create({ id: containerName });
The statusCode is an HTTP response code. A successful response is in the 200-299 range.
Access a container
A container is accessed from the Container object either directly or chained from the CosmosClient or Database objects.
const databaseName = 'myDb';
const containerName = 'myContainer';
// Chained - assumes database and container already exis
const { container, statusCode } = await client.database(databaseName).container(containerName);
// Direct - assumes database and container already exist
const { database, statusCode } = await client.database(databaseName);
if(statusCode < 400){
const { container, statusCode } = await database.container(containerName);
}
// Query - assumes database and container already exist
const { resources } = await client.database(databaseName).containers
.query({
query: `SELECT * FROM root r where r.id =@containerId`,
parameters: [
{
name: '@containerId',
value: containerName
}
]
})
.fetchAll();
Access by object:
- Containers (plural): Create or query containers.
- Container (singular): Delete container, work with items.
Delete a container
Once you get the Container object, you can use the Container object to delete the container:
const { statusCode } = await container.delete();
The statusCode is an HTTP response code. A successful response is in the 200-299 range.
Next steps
Now that you've create a container, use the next guide to create items.