Simple CRUD Operations In Azure Cosmos DB

Introduction

  • This article will help the beginners to perform CRUD operations on Cosmos DB database using C#.
  • If you are new to Cosmos DB, then please refer Getting Started with Cosmos DB article.

Let’s start.

  • Create Solution and add NuGet Package
    1. Create a new console app.
    2. Right-click on Project -> Manage NuGet Package.
    3. Search for ‘documentdb’ under the "Browse" tab.
    4. Select Microsoft.Azure.DocumentDB package and click on Install.

      Cosmos DB

  • Add Config Settings
    Go to App Settings and add the following configuration.
    1. <appSettings>  
    2.   <!--Add Cosmos DB Endpoint URL-->  
    3.   <add key="DocDbEndpoint" value =""/>  
    4.    <!--Add Primary Key-->  
    5.   <add key="DocDbMasterKey" value =""/>  
    6. </appSettings>  

  • How to get Endpoint URL and Master Key?

    1. Open Azure portal.
    2. Go to Cosmos DB account.
    3. Click on Keys.
    4. Copy the URI and Primary Key.

      Cosmos DB

    5. URI = DocDbEndpoint
    6. Primary Key = DocDbMasterKey

  • Initialize Document Client Instance

    1. Add reference to Configuration;
    2. Add reference to Microsoft.Azure.Documents.Client;
    3. Retrieve Endpoint URL and Primary Key
      1. using Microsoft.Azure.Documents;  
      2. using Microsoft.Azure.Documents.Client;  
      3. using System;  
      4. using System.Configuration;  
      5. using System.Linq;  
      6. using System.Threading.Tasks;  
      7.   
      8. namespace CosmosDBCrudOperationd  
      9. {  
      10.     class Program  
      11.     {  
      12.         static void Main(string[] args)  
      13.         {  
      14.             Task.Run(async () =>  
      15.             {  
      16.                   var endpoint = ConfigurationManager.AppSettings["DocDbEndpoint"];  
      17.                 var masterKey = ConfigurationManager.AppSettings["DocDbMasterKey"];  
      18.                 using (var client = new DocumentClient(new Uri(endpoint), masterKey))  
      19.                 {  
      20.                     
      21.                 }  
      22.   
      23.             }).Wait();  
      24.         }  
      25.     }  
      26. }  

  • Create a New Cosmos DB Database
    1. Console.WriteLine("\r\n>>>>>>>>>>>>>>>> Creating Database <<<<<<<<<<<<<<<<<<<");  
    2. // Create new database Object  
    3. //Id defines name of the database  
    4. var databaseDefinition = new Database { Id = "testDb" };  
    5. var database = await client.CreateDatabaseIfNotExistsAsync(databaseDefinition);  
    6. Console.WriteLine("Database testDb created successfully");  

  • Create a new database collection.

    A database is a container that holds the number of collections.

    To create a new collection, you need to give the path of the database under which you want to create the collection.

    Database path can be given in following format,
    dbo/{databaseName}
    1. //Create new database collection  
    2. Console.WriteLine("\r\n>>>>>>>>>>>>>>>> Creating Collection <<<<<<<<<<<<<<<<<<<");     
    3. var collectionDefinition = new DocumentCollection { Id = "testDocumentCollection" };  
    4. var collection = await client.CreateDocumentCollectionIfNotExistsAsync("dbo/testDb",   
    5.     collectionDefinition);  
    6. Console.WriteLine("Collection testDocumentCollection created successfully");  

You can see that CreateDocumentCollectionIfNotExistsAsync accepts two parameters.

  1. Database Link (path to database): dbo/testDb
  2. Document Collection Object

    Alternatively, you can use UriFactory.CreateDatabaseUri(databaseName) method to create database URI for you.
    1. //Create new database collection  
    2.  Console.WriteLine("\r\n>>>>>>>>>>>>>>>> Creating Collection <<<<<<<<<<<<<<<<<<<");                     
    3.  var collectionDefinition = new DocumentCollection { Id = "testDocumentCollection" };  
    4.  var collection = await client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("testDb"),  
    5.      collectionDefinition);  
    6.  Console.WriteLine("Collection testDocumentCollection created successfully");  

  • Insert New Document in Collection
    To insert new document, you need two things.

    1. Path to collection: dbo/{databaseName}/colls/{collectionName}
    2. Document Object
      1. //Insert new Document  
      2.  Console.WriteLine("\r\n>>>>>>>>>>>>>>>> Creating Document <<<<<<<<<<<<<<<<<<<");  
      3.  dynamic doc1Definition = new  
      4.  {  
      5.      title = "Star War IV ",  
      6.      rank = 600,  
      7.      category = "Sci-fi"  
      8.  };  
      9.  var document1 = await client.CreateDocumentAsync(  
      10.      UriFactory.CreateDocumentCollectionUri("testDb""testDocumentCollection"),  
      11.      doc1Definition);  

Here, doc1Definatin defines the document we want to insert in Cosmos DB.

UriFactory.CreateDocumentCollectionUri("testDb", "testDocumentCollection") method is used to create the collection URI “dbo/testDb/colls/testDocumentCollection”.

Query Inserted Document
  1. Console.WriteLine("\r\n>>>>>>>>>>>> Querying Document <<<<<<<<<<<<<<<<<<<<");  
  2.  var response = client.CreateDocumentQuery  
  3.  (UriFactory.CreateDocumentCollectionUri("testDb""testDocumentCollection"),   
  4.      "select * from c").ToList();  
  5.  var document = response.First();  
  6.  Console.WriteLine($"Id:{document.id}");  
  7.  Console.WriteLine($"Title:{document.title}");  
  8.  Console.WriteLine($"Rank:{document.rank}");  
  9.  Console.WriteLine($"category:{document.category}");  

CreateDocumentQuery method requires two parametes,

  1. Collection URI
  2. Query string

Delete Collection
  1. Console.WriteLine("\r\n>>>>>>>>>>>>>>>> Deleteing Collection <<<<<<<<<<<<<<<<<<<");  
  2. await client.DeleteDocumentCollectionAsync(  
  3.     UriFactory.CreateDocumentCollectionUri("testDb""testDocumentCollection"));  

Overall Code

  1. using Microsoft.Azure.Documents;  
  2. using Microsoft.Azure.Documents.Client;  
  3. using System;  
  4. using System.Configuration;  
  5. using System.Linq;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace CosmosDBCrudOperationd  
  9. {  
  10.     class Program  
  11.     {  
  12.         static void Main(string[] args)  
  13.         {  
  14.             Task.Run(async () =>  
  15.             {  
  16.                 var endpoint = ConfigurationManager.AppSettings["DocDbEndpoint"];  
  17.                 var masterKey = ConfigurationManager.AppSettings["DocDbMasterKey"];  
  18.                 using (var client = new DocumentClient(new Uri(endpoint), masterKey))  
  19.                 {  
  20.                     Console.WriteLine("\r\n>>>>>>>>>>>>>>>> Creating Database <<<<<<<<<<<<<<<<<<<");  
  21.                     // Create new database Object  
  22.                     //Id defines name of the database  
  23.                     var databaseDefinition = new Database { Id = "testDb" };  
  24.                     var database = await client.CreateDatabaseIfNotExistsAsync(databaseDefinition);  
  25.                     Console.WriteLine("Database testDb created successfully");  
  26.                       
  27.                     //Create new database collection  
  28.                     Console.WriteLine("\r\n>>>>>>>>>>>>>>>> Creating Collection <<<<<<<<<<<<<<<<<<<");                     
  29.                     var collectionDefinition = new DocumentCollection { Id = "testDocumentCollection" };  
  30.                     var collection = await client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("testDb"),   
  31.                         collectionDefinition);  
  32.                     Console.WriteLine("Collection testDocumentCollection created successfully");  
  33.   
  34.                     //Insert new Document  
  35.                     Console.WriteLine("\r\n>>>>>>>>>>>>>>>> Creating Document <<<<<<<<<<<<<<<<<<<");  
  36.                     dynamic doc1Definition = new  
  37.                     {  
  38.                         title = "Star War IV ",  
  39.                         rank = 600,  
  40.                         category = "Sci-fi"  
  41.                     };  
  42.                     var document1 = await client.CreateDocumentAsync(  
  43.                         UriFactory.CreateDocumentCollectionUri("testDb""testDocumentCollection"),  
  44.                         doc1Definition);  
  45.   
  46.                     Console.WriteLine("\r\n>>>>>>>>>>>> Querying Document <<<<<<<<<<<<<<<<<<<<");  
  47.                     var response = client.CreateDocumentQuery(UriFactory.CreateDocumentCollectionUri("testDb""testDocumentCollection"),   
  48.                         "select * from c").ToList();  
  49.                     var document = response.First();  
  50.                     Console.WriteLine($"Id:{document.id}");  
  51.                     Console.WriteLine($"Title:{document.title}");  
  52.                     Console.WriteLine($"Rank:{document.rank}");  
  53.                     Console.WriteLine($"category:{document.category}");  
  54.   
  55.                     Console.WriteLine("\r\n>>>>>>>>>>>>>>>> Deleteing Collection <<<<<<<<<<<<<<<<<<<");  
  56.                     await client.DeleteDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri("testDb""testDocumentCollection"));  
  57.   
  58.                     Console.ReadKey();  
  59.                 }  
  60.   
  61.             }).Wait();  
  62.         }  
  63.     }  
  64. }