Azure Document DB CRUD Operation

Introduction

This article explains how to create documents in SQL (DocumentDB) API. Before starting, we need to understand what is documented and how it works. SQL (DocumentDB) API is one of the APIs that comes under Azure COSMOS DB.

Azure Cosmos Db

This is one of the most important parts of Microsoft Azure. Azure Cosmos Db has a globally distributed database. It has lots of features available like global distribution, which means turnkey distribution in more than 30 regions, you can scale it horizontally (scale storage and throughput), and low latency, which means it gives high performance (99.999% read in < 10ms and 99.99% write-in <15ms), also it is highly available.

Cosmos Db has the following multi-model APIs,

  1. SQL API(DocumentDB)
  2. MongoDB API
  3. Gremlin API(GraphDB)
  4. Table API
  5. Cassandra API

So, let’s start with DocumentDB

Azure Cosmos Db SQL API has all the features mentioned above.

  1. Create Azure Cosmos DB database
    Click Create a Resource> Databases > Azure Cosmos DB.
    Azure Cosmos Db database
  2. Create a Cosmos DB account.
    • Enter the Account ID
    • API as SQL API
    • Subscription whatever you have
    • Resource Group. 
    • Location etc
      Cosmos DB account
  3. Now, we will create a collection. Collections are like containers in which we can create documents, and documents are JSON objects.
    Enter the Database ID, Collection ID, and throughput as shown in the below screenshot.
    JSON objects
    We created resources manually over the Azure portal, you can also create them by coding.
    Let’s start the coding for creating documents in the ToDoList Collection.
  4. Create a console application. I have created it in the dot net core 2.0.
    Console application
  5. Install NuGet for SQL API into the DocumentDbDemo project. So we can connect with the Azure document DB.
    Nugget for SQL API
  6. Get the connection string of cosmos DB (we created earlier ) from the Azure portal.
    Connection string of cosmos Db
  7. Create an appsetting.json file. I have created an environment-specific file for the development environment. So we can check in the program file, and we will see in the code.
    Appsetting.json
  8. We will create a Config. cs class that will contain the properties to get the values of the appsettings.dev.json file.
    public class Config
    {
        public DocDbConnectionString docDb { get; set; }
    }
    
    public class DocDbConnectionString
    {
        public string EndPoint { get; set; }
        public string AuthKey { get; set; }
        public string Database { get; set; }
        public string Collection { get; set; }
    }
    
  9. Let’s come to the program.cs file and do the basic configuration code.
    First, set the environment variable -- right-click on
    DocumentDbDemo>Debug>Add>ASPNETCORE_ENVIRONMENT=dev. So you will get the dev
    environment file in program.cs.
    class Program
    {
        private static IConfiguration Configuration { get; set; }
        private static Config configs;
        private DocumentClient client;
    
        static void Main(string[] args)
        {
            // Setup Configuration
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: false, reloadOnChange: true);
            Configuration = builder.Build();
            configs = new Config();
            Configuration.Bind(configs);
    
            Program obj = new Program();
            obj.CRUDOperation().Wait();
        }
    
        // Get a single instance of Document client and reuse
        public DocumentClient Client
        {
            get
            {
                if (client == null)
                {
                    Uri endpointUri = new Uri(configs.docDb.EndPoint);
                    client = new DocumentClient(endpointUri, configs.docDb.AuthKey, null, ConsistencyLevel.Session);
                    client.OpenAsync();
                }
                return client;
            }
        }
    }
    
    In the above class, we have defined some static properties and variables, also we've also created the client of Document DB. It will create a single instance and will reuse or we can say singleton design pattern.
  10. Next, we will code to create a document into the collection of documentDB.
    var collection = UriFactory.CreateDocumentCollectionUri(configs.docDb.Database, configs.docDb.Collection);
    
    // create JObject which contains the employee details
    Console.WriteLine("\nCreating document");
    JObject emp = new JObject();
    emp.Add("id", "V001");
    emp.Add("name", "virendra");
    emp.Add("address", "Indore");
    emp.Add("Country", "India");
    // create the document
    var createResponse = await Client.CreateDocumentAsync(collection, emp);
    var createdDocument = createResponse.Resource;
    
    Console.WriteLine("Document with id {0} created", createdDocument.Id);
    
    Now, you can check the document in the collection ToDoList as shown in the below image,
    ToDoList
  11. Now, we can read that created document by Id
    // Read document by Id
    readResponse = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"));
    var readDocument = readResponse.Resource;
    Console.WriteLine("Read Document {0}: ", readResponse.Resource.ToString());
    
    See the below as output,
    Output
  12. Now, we will go for updating the document by changing the value of the address property.
    // create JObject which contains the employee
    JObject updateEmp = new JObject();
    updateEmp.Add("id", "V001");
    updateEmp.Add("name", "virendra");
    updateEmp.Add("address", "pune");
    updateEmp.Add("Country", "India");
    
    Console.WriteLine("\nUpdating and Adding new property to document");
    // now update the document
    var updateResponse = await Client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"), updateEmp);
    var updated = updateResponse.Resource;
    Console.WriteLine("Document with id {0} Updated", updated.Id);
    
    See the below image of the updated document.
    Updated document
  13. Now, we will finally delete that document from the collection. 
    // Delete the Document
    var deleteResponse = await Client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"));
    Console.WriteLine("Document Deleted");
    
    See, deleted V001 document from the collection.
    Deleted V001 document
    Below is the completed code of the program.cs class.
    class Program
    {
        private static IConfiguration Configuration { get; set; }
        private static Config configs;
        private DocumentClient client;
    
        static void Main(string[] args)
        {
            // Setup Configuration
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: false, reloadOnChange: true);
            Configuration = builder.Build();
            configs = new Config();
            Configuration.Bind(configs);
    
            Program obj = new Program();
            obj.CRUDOperation().Wait();
        }
    
        // CRUD Operation
        private async Task CRUDOperation()
        {
            var collection = UriFactory.CreateDocumentCollectionUri(configs.docDb.Database, configs.docDb.Collection);
            try
            {
                // Create JObject containing the employee details
                Console.WriteLine("\nCreating document");
                JObject emp = new JObject();
                emp.Add("id", "V001");
                emp.Add("name", "virendra");
                emp.Add("address", "Indore");
                emp.Add("Country", "India");
                // Create the document
                var createResponse = await Client.CreateDocumentAsync(collection, emp);
                var createdDocument = createResponse.Resource;
    
                Console.WriteLine("Document with id {0} created", createdDocument.Id);
            }
            catch (DocumentClientException docEx)
            {
                if (docEx.StatusCode == HttpStatusCode.Conflict)
                {
                    // Create JObject containing the employee
                    JObject updateEmp = new JObject();
                    updateEmp.Add("id", "V001");
                    updateEmp.Add("name", "virendra");
                    updateEmp.Add("address", "pune");
                    updateEmp.Add("Country", "India");
    
                    Console.WriteLine("\nUpdating and Adding new property to document");
                    // Now update the document
                    var updateResponse = await Client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"), updateEmp);
                    var updated = updateResponse.Resource;
                    Console.WriteLine("Document with id {0} Updated", updated.Id);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
    
            // Read document by Id
            var readResponse = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"));
            var readDocument = readResponse.Resource;
            Console.WriteLine("Read Document {0}: ", readResponse.Resource.ToString());
    
            // Delete the Document
            var deleteResponse = await Client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"));
            Console.WriteLine("Document Deleted");
            Console.ReadKey();
        }
    
        // Get a single instance of Document client and reuse
        public DocumentClient Client
        {
            get
            {
                if (client == null)
                {
                    Uri endpointUri = new Uri(configs.docDb.EndPoint);
                    client = new DocumentClient(endpointUri, configs.docDb.AuthKey, null, ConsistencyLevel.Session);
                    client.OpenAsync();
                }
                return client;
            }
        }
    }
    

I hope this code will help you … happy coding.

Thank you.


Similar Articles