Create and update documents with the Azure Cosmos DB for NoSQL SDK
The Microsoft.Azure.Cosmos.Container class includes a set of member methods to create, retrieve, update, and delete items within an Azure Cosmos DB for NoSQL container. Together, these methods perform some of the most common โCRUDโ operations across various items within NoSQL API containers.
In this lab, youโll use the SDK to perform everyday CRUD operations on an item within an Azure Cosmos DB for NoSQL container.
Prepare your development environment
If you have not already cloned the lab code repository for DP-420 to the environment where youโre working on this lab, follow these steps to do so. Otherwise, open the previously cloned folder in Visual Studio Code.
-
Start Visual Studio Code.
๐ If you are not already familiar with the Visual Studio Code interface, review the Getting Started documentation
-
Open the command palette and run Git: Clone to clone the
https://github.com/microsoftlearning/dp-420-cosmos-db-dev
GitHub repository in a local folder of your choice.๐ก You can use the CTRL+SHIFT+P keyboard shortcut to open the command palette.
-
Once the repository has been cloned, open the local folder you selected in Visual Studio Code.
Create an Azure Cosmos DB for NoSQL account
Azure Cosmos DB is a cloud-based NoSQL database service that supports multiple APIs. When provisioning an Azure Cosmos DB account for the first time, you will select which of the APIs you want the account to support (for example, Mongo API or NoSQL API). Once the Azure Cosmos DB for NoSQL account is done provisioning, you can retrieve the endpoint and key and use them to connect to the Azure Cosmos DB for NoSQL account using the Azure SDK for .NET or any other SDK of your choice.
-
In a new web browser window or tab, navigate to the Azure portal (
portal.azure.com
). -
Sign into the portal using the Microsoft credentials associated with your subscription.
-
Select + Create a resource, search for Cosmos DB, and then create a new Azure Cosmos DB for NoSQL account resource with the following settings, leaving all remaining settings to their default values:
Setting Value Subscription Your existing Azure subscription Resource group Select an existing or create a new resource group Account Name Enter a globally unique name Location Choose any available region Capacity mode Provisioned throughput Apply Free Tier Discount Do Not Apply ๐ Your lab environments may have restrictions preventing you from creating a new resource group. If that is the case, use the existing pre-created resource group.
-
Wait for the deployment task to complete before continuing with this task.
-
Go to the newly created Azure Cosmos DB account resource and navigate to the Keys pane.
-
This pane contains the connection details and credentials necessary to connect to the account from the SDK. Specifically:
-
Notice the URI field. You will use this endpoint value later in this exercise.
-
Notice the PRIMARY KEY field. You will use this key value later in this exercise.
-
-
Switch back to Visual Studio Code.
Connect to the Azure Cosmos DB for NoSQL account from the SDK
Using the credentials from the newly created account, you will connect with the SDK classes and create a new database and container instance. Then, you will use the Data Explorer to validate that the instances exist in the Azure portal.
-
In Visual Studio Code, in the Explorer pane, browse to the 06-sdk-crud folder.
-
Open the context menu for the 06-sdk-crud folder and then select Open in Integrated Terminal to open a new terminal instance.
๐ This command will open the terminal with the starting directory already set to the 06-sdk-crud folder.
-
Add the Microsoft.Azure.Cosmos package from NuGet using the following command:
dotnet add package Microsoft.Azure.Cosmos --version 3.22.1
-
Build the project using the dotnet build command:
dotnet build
-
Close the integrated terminal.
-
Open the script.cs code file within the 06-sdk-crud folder.
๐ The Microsoft.Azure.Cosmos library has already been pre-imported from NuGet.
-
Locate the string variable named endpoint. Set its value to the endpoint of the Azure Cosmos DB account you created earlier.
string endpoint = "<cosmos-endpoint>";
๐ For example, if your endpoint is: httpsยญ://dp420.documents.azure.com:443/, then the C# statement would be: string endpoint = โhttpsยญ://dp420.documents.azure.com:443/โ;.
-
Locate the string variable named key. Set its value to the key of the Azure Cosmos DB account you created earlier.
string key = "<cosmos-key>";
๐ For example, if your key is: fDR2ci9QgkdkvERTQ==, then the C# statement would be: string key = โfDR2ci9QgkdkvERTQ==โ;.
-
Asynchronously invoke the CreateDatabaseIfNotExistsAsync method of the client variable passing in the name of the new database (cosmicworks) you would like to create, and storing the result in a variable of type Database:
Database database = await client.CreateDatabaseIfNotExistsAsync("cosmicworks");
-
Asynchronously invoke the CreateContainerIfNotExistsAsync method of the database variable passing in the name of the new container (products), the partition key path (/categoryId), and the throughput (400) you would like to create within the cosmicworks database and storing the result in a variable of type Container:
Container container = await database.CreateContainerIfNotExistsAsync("products", "/categoryId", 400);
-
Once you are done, your code file should now include:
using System; using Microsoft.Azure.Cosmos; string endpoint = "<cosmos-endpoint>"; string key = "<cosmos-key>"; CosmosClient client = new CosmosClient(endpoint, key); Database database = await client.CreateDatabaseIfNotExistsAsync("cosmicworks"); Container container = await database.CreateContainerIfNotExistsAsync("products", "/categoryId", 400);
-
Save the script.cs code file.
-
In Visual Studio Code, open the context menu for the 06-sdk-crud folder and then select Open in Integrated Terminal to open a new terminal instance.
-
Build and run the project using the dotnet run command:
dotnet run
-
Close the integrated terminal.
-
Switch to your web browser window.
-
Within the Azure Cosmos DB account resource, navigate to the Data Explorer pane.
-
In the Data Explorer, expand the cosmicworks database node, then observe the new products container node within the NOSQL API navigation tree.
Perform create and read point operations on items with the SDK
You will now use the set of asynchronous methods in the Microsoft.Azure.Cosmos.Container class to perform common operations on items within a NoSQL API container. These operations are all done using the task asynchronous programming model in C#.
-
Return to Visual Studio Code. Open the product.cs code file within the 06-sdk-crud folder.
๐ Do not close the editor for the script.cs file.
-
Observe the Product class within this code file. This class represents a product item that will be stored and manipulated within this container.
-
Return to the editor tab for the script.cs code file.
-
Create a new object of type Product named saddle with the following properties:
Property Value id 706cd7c6-db8b-41f9-aea2-0e0c7e8eb009 categoryId 9603ca6c-9e28-4a02-9194-51cdb7fea816 name Road Saddle price 45.99d tags { tan, new, crisp } Product saddle = new() { id = "706cd7c6-db8b-41f9-aea2-0e0c7e8eb009", categoryId = "9603ca6c-9e28-4a02-9194-51cdb7fea816", name = "Road Saddle", price = 45.99d, tags = new string[] { "tan", "new", "crisp" } };
-
Asynchronously invoke the generic CreateItemAsync<> method of the container variable passing in the saddle variable as the method parameter and using Product as the generic type:
await container.CreateItemAsync<Product>(saddle);
-
Once you are done, your code file should now include:
using System; using Microsoft.Azure.Cosmos; string endpoint = "<cosmos-endpoint>"; string key = "<cosmos-key>"; CosmosClient client = new CosmosClient(endpoint, key); Database database = await client.CreateDatabaseIfNotExistsAsync("cosmicworks"); Container container = await database.CreateContainerIfNotExistsAsync("products", "/categoryId", 400); Product saddle = new() { id = "706cd7c6-db8b-41f9-aea2-0e0c7e8eb009", categoryId = "9603ca6c-9e28-4a02-9194-51cdb7fea816", name = "Road Saddle", price = 45.99d, tags = new string[] { "tan", "new", "crisp" } }; await container.CreateItemAsync<Product>(saddle);
-
Save the script.cs code file.
-
In Visual Studio Code, open the context menu for the 06-sdk-crud folder and then select Open in Integrated Terminal to open a new terminal instance.
-
Build and run the project using the dotnet run command:
dotnet run
-
Close the integrated terminal.
-
Return to the editor tab for the script.cs code file.
-
Delete the following lines of code:
Product saddle = new() { id = "706cd7c6-db8b-41f9-aea2-0e0c7e8eb009", categoryId = "9603ca6c-9e28-4a02-9194-51cdb7fea816", name = "Road Saddle", price = 45.99d, tags = new string[] { "tan", "new", "crisp" } }; await container.CreateItemAsync<Product>(saddle);
-
Create a string variable named id with a value of 706cd7c6-db8b-41f9-aea2-0e0c7e8eb009:
string id = "706cd7c6-db8b-41f9-aea2-0e0c7e8eb009";
-
Create a string variable named categoryId with a value of 9603ca6c-9e28-4a02-9194-51cdb7fea816:
string categoryId = "9603ca6c-9e28-4a02-9194-51cdb7fea816";
-
Create a variable of type PartitionKey named partitionKey passing in the categoryId variable as a constructor parameter:
PartitionKey partitionKey = new (categoryId);
-
Asynchronously invoke the generic ReadItemAsync<> method of the container variable passing in the id and partitionkey variables as method parameters, using Product as the generic type, and storing the result in a variable named saddle of type Product:
Product saddle = await container.ReadItemAsync<Product>(id, partitionKey);
-
Invoke the static Console.WriteLine method to print the saddle object using a formatted output string:
Console.WriteLine($"[{saddle.id}]\t{saddle.name} ({saddle.price:C})");
-
Once you are done, your code file should now include:
using System; using Microsoft.Azure.Cosmos; string endpoint = "<cosmos-endpoint>"; string key = "<cosmos-key>"; CosmosClient client = new CosmosClient(endpoint, key); Database database = await client.CreateDatabaseIfNotExistsAsync("cosmicworks"); Container container = await database.CreateContainerIfNotExistsAsync("products", "/categoryId", 400); string id = "706cd7c6-db8b-41f9-aea2-0e0c7e8eb009"; string categoryId = "9603ca6c-9e28-4a02-9194-51cdb7fea816"; PartitionKey partitionKey = new (categoryId); Product saddle = await container.ReadItemAsync<Product>(id, partitionKey); Console.WriteLine($"[{saddle.id}]\t{saddle.name} ({saddle.price:C})");
-
Save the script.cs code file.
-
In Visual Studio Code, open the context menu for the 06-sdk-crud folder and then select Open in Integrated Terminal to open a new terminal instance.
-
Build and run the project using the dotnet run command:
dotnet run
-
Observe the output from the terminal. Specifically, observe the formatted output text with the id, name, and price from the item.
-
Close the integrated terminal.
Perform update and delete point operations with the SDK
While learning the SDK, itโs not uncommon to use an online Azure Cosmos DB SDK account or the emulator to update an item and oscillate back-and-forth between the Data Explorer and your IDE of choice as you perform an operation and check to see if your change has been applied. Here, you will do just that as you update and delete an item using the SDK.
-
Return to your web browser window or tab.
-
Within the Azure Cosmos DB account resource, navigate to the Data Explorer pane.
-
In the Data Explorer, expand the cosmicworks database node, then expand the new products container node within the NOSQL API navigation tree.
-
Select the Items node. Select the only item within the container and then observe the values of the name and price properties of the item.
Property Value Name Road Saddle Price $45.99 ๐ At this point in time, these values should not have been changed since you have created the item. You will change these values in this exercise.
-
Return to Visual Studio Code. Return to the editor tab for the script.cs code file.
-
Delete the following lines of code:
Console.WriteLine($"[{saddle.id}]\t{saddle.name} ({saddle.price:C})");
-
Change the saddle variable by setting the value of the price property to 32.55:
saddle.price = 32.55d;
-
Modify the saddle variable again by setting the value of the name property to Road LL Saddle:
saddle.name = "Road LL Saddle";
-
Asynchronously invoke the generic UpsertItemAsync<> method of the container variable passing in the saddle variable as the method parameter and using Product as the generic type:
await container.UpsertItemAsync<Product>(saddle);
-
Once you are done, your code file should now include:
using System; using Microsoft.Azure.Cosmos; string endpoint = "<cosmos-endpoint>"; string key = "<cosmos-key>"; CosmosClient client = new CosmosClient(endpoint, key); Database database = await client.CreateDatabaseIfNotExistsAsync("cosmicworks"); Container container = await database.CreateContainerIfNotExistsAsync("products", "/categoryId", 400); string id = "706cd7c6-db8b-41f9-aea2-0e0c7e8eb009"; string categoryId = "9603ca6c-9e28-4a02-9194-51cdb7fea816"; PartitionKey partitionKey = new (categoryId); Product saddle = await container.ReadItemAsync<Product>(id, partitionKey); saddle.price = 32.55d; saddle.name = "Road LL Saddle"; await container.UpsertItemAsync<Product>(saddle);
-
Save the script.cs code file.
-
In Visual Studio Code, open the context menu for the 06-sdk-crud folder and then select Open in Integrated Terminal to open a new terminal instance.
-
Build and run the project using the dotnet run command:
dotnet run
-
Close the integrated terminal.
-
Return to your web browser window or tab.
-
Within the Azure Cosmos DB account resource, navigate to the Data Explorer pane.
-
In the Data Explorer, expand the cosmicworks database node, then expand the new products container node within the NOSQL API navigation tree.
-
Select the Items node. Select the only item within the container and then observe the values of the name and price properties of the item.
Property Value Name Road LL Saddle Price $32.55 ๐ At this point in time, these values should have been changed since you have observed the item.
-
Return to Visual Studio Code. Return to the editor tab for the script.cs code file.
-
Delete the following lines of code:
Product saddle = await container.ReadItemAsync<Product>(id, partitionKey); saddle.price = 32.55d; saddle.name = "Road LL Saddle"; await container.UpsertItemAsync<Product>(saddle);
-
Asynchronously invoke the generic DeleteItemAsync<> method of the container variable passing in the id and partitionkey variables as method parameters and using Product as the generic type:
await container.DeleteItemAsync<Product>(id, partitionKey);
-
Save the script.cs code file.
-
In Visual Studio Code, open the context menu for the 06-sdk-crud folder and then select Open in Integrated Terminal to open a new terminal instance.
-
Build and run the project using the dotnet run command:
dotnet run
-
Close the integrated terminal.
-
Return to your web browser window or tab.
-
Within the Azure Cosmos DB account resource, navigate to the Data Explorer pane.
-
In the Data Explorer, expand the cosmicworks database node, then expand the new products container node within the NOSQL API navigation tree.
-
Select the Items node. Observe that the items list is now empty.
-
Close your web browser window or tab.
-
Close Visual Studio Code.