Azure Cosmos DB Documentation

Add Items to Azure Cosmos DB

This tutorial guides you through the process of adding new items (documents) to your Azure Cosmos DB container using various SDKs. We'll cover the fundamental concepts and provide code examples.

Prerequisite: Ensure you have an Azure Cosmos DB account and a database with a container created. If not, please follow the Create Azure Cosmos DB Resource tutorial first.

Understanding Item Operations

In Azure Cosmos DB, data is stored as JSON documents. Adding an item means creating a new JSON document within a specified container. The Azure Cosmos DB SDKs simplify this process by providing methods to serialize your data objects into JSON and send them to the database.

Adding a Single Item

The most common way to add an item is by using the `CreateItemAsync` (or equivalent) method provided by the Azure Cosmos DB SDK. This method takes your data object and optionally a partition key value as arguments.

Example using the .NET SDK

using Microsoft.Azure.Cosmos;
using System.Threading.Tasks;

// Assume 'container' is an initialized CosmosContainer object
// Assume 'newItem' is an object representing your data

// Example data item
public class Product
{
    public string id { get; set; }
    public string name { get; set; }
    public double price { get; set; }
    public string category { get; set; }
}

// Add the item
var newItem = new Product
{
    id = Guid.NewGuid().ToString(), // Unique identifier
    name = "Laptop",
    price = 1200.50,
    category = "Electronics"
};

try
{
    // For containers with partition keys, you need to specify the partition key value
    var response = await container.CreateItemAsync(newItem, new PartitionKey(newItem.category));
    Console.WriteLine($"Item created with ID: {response.Resource.id}");
}
catch (CosmosException ex)
{
    Console.WriteLine($"Error creating item: {ex.StatusCode}");
}

Adding Multiple Items (Bulk Operations)

For scenarios where you need to insert a large number of items efficiently, Azure Cosmos DB offers bulk operations. This can significantly improve performance and reduce costs compared to individual item insertions.

Bulk operations are supported by specific SDK versions and might require dedicated configuration. Consult the relevant SDK documentation for details on implementing bulk imports.

The general approach for bulk operations often involves:

Considerations for Partition Keys

When adding items to a container that uses a partition key, you must provide the partition key value for each item. The partition key helps Azure Cosmos DB distribute your data and requests across physical partitions. Failing to provide a partition key when required will result in an error.

Choosing an effective partition key is crucial for performance and scalability. Ensure your partition key distributes requests evenly and avoids hot partitions.

Next Steps

Now that you know how to add items, you can explore other fundamental operations: