3. Press the “Create” button in the Azure CosmosDB for NoSQL
4. Set the Subscription, the resource group, the account name, the location, select the capacity mode,�apply the free tier discount, limit total account throughput and press the button “Review + create”
5. Azure CosmosDB structure
6. Press the CosmosDB link “luiscococosmosdb” to navigate to the Azure CosmosDB account
7. In the Azure CosmosDB account go to the “Keys” option
8. Set the environmental variables values: the COSMOS_ENDPOINT and the COSMOS_KEY
9. Source code
using Microsoft.Azure.Cosmos;usingCosmosClientclient=new(
accountEndpoint: Environment.GetEnvironmentVariable("COSMOS_ENDPOINT")!,
authKeyOrResourceToken: Environment.GetEnvironmentVariable("COSMOS_KEY")!);//1. Create a databaseDatabasedatabase=await client.CreateDatabaseIfNotExistsAsync(
id:"cosmicworks");
Console.WriteLine($"New database:\t{database.Id}");//2. Container reference with creation if it does not already existContainercontainer=await database.CreateContainerIfNotExistsAsync(
id:"products",
partitionKeyPath:"/categoryId",
throughput:400);
Console.WriteLine($"New container:\t{container.Id}");//3. Create new object and upsert (create or replace) to containerProductnewItem=new(
id:"70b63682-b93a-4c77-aad2-65501347265f",
categoryId:"61dba35b-4f02-45c5-b648-c6badc0cbd79",
categoryName:"gear-surf-surfboards",
name:"Yamba Surfboard",
quantity:12,
sale:false);ProductcreatedItem=await container.CreateItemAsync<Product>(
item: newItem,
partitionKey:new PartitionKey("61dba35b-4f02-45c5-b648-c6badc0cbd79"));
Console.WriteLine($"Created item:\t{createdItem.id}\t[{createdItem.categoryName}]");//4. Point read item from container using the id and partitionKeyProductreadItem=await container.ReadItemAsync<Product>(
id:"70b63682-b93a-4c77-aad2-65501347265f",
partitionKey:new PartitionKey("61dba35b-4f02-45c5-b648-c6badc0cbd79"));//5. Create query using a SQL string and parametersvarquery=new QueryDefinition(
query:"SELECT * FROM products p WHERE p.categoryId = @categoryId").WithParameter("@categoryId","61dba35b-4f02-45c5-b648-c6badc0cbd79");usingFeedIterator<Product>feed= container.GetItemQueryIterator<Product>(
queryDefinition: query
);while(feed.HasMoreResults){FeedResponse<Product>response=await feed.ReadNextAsync();foreach(Product item in response){
Console.WriteLine($"Found item:\t{item.name}");}}
10. Press in the "Data Explorer" option to access the ComosDB database