Introduction

Azure Cosmos DB, a globally distributed, multi-model NoSQL database service, supports CRUD operations for storing and retrieving data. In this guide, we'll explore the fundamental CRUD operations (Create, Read, Update, Delete) in Azure Cosmos DB and provide sample code to help you get started.


Prerequisites

Before you begin, ensure you have the following prerequisites in place:

  • An Azure Cosmos DB account.
  • Connection details, including the endpoint and authorization key.
  • A programming environment for writing and running code (e.g., Visual Studio, VS Code, or a code editor of your choice).

Sample Code: CRUD Operations in .NET

Here's an example of performing CRUD operations in Azure Cosmos DB using the .NET SDK:

Create Document

using Microsoft.Azure.Cosmos;
using System;
var endpoint = "YourEndpoint";
var key = "YourKey";
var databaseId = "YourDatabaseId";
var containerId = "YourContainerId";
var client = new CosmosClient(endpoint, key);
var database = client.GetDatabase(databaseId);
var container = database.GetContainer(containerId);
var item = new YourModel { /* Your data properties */ };
var response = await container.CreateItemAsync(item);

Read Document

var documentId = "YourDocumentId";
var partitionKey = new PartitionKey("YourPartitionKey");
var response = await container.ReadItemAsync(documentId, partitionKey);
var item = response.Resource;

Update Document

var documentId = "YourDocumentId";
var partitionKey = new PartitionKey("YourPartitionKey");
var response = await container.ReadItemAsync(documentId, partitionKey);
var item = response.Resource;
// Make changes to the item
var updateResponse = await container.ReplaceItemAsync(item, documentId, partitionKey);

Delete Document

var documentId = "YourDocumentId";
var partitionKey = new PartitionKey("YourPartitionKey");
var response = await container.DeleteItemAsync(documentId, partitionKey);

Conclusion

Basic CRUD operations in Azure Cosmos DB are essential for building applications that rely on flexible, scalable, and globally distributed data storage. By following the steps and using sample code outlined in this guide, you can effectively create, read, update, and delete documents in Azure Cosmos DB.