Introduction
This article explains how to create documents in SQL (DocumentDB) API. Before starting, we need to understand what is documentDb 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), 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,
- SQL API(DocumentDB)
- MongoDB API
- Gremlin API(GraphDB)
- Table API
- Cassandra API
So, let’s start with DocumentDB
Azure Cosmos Db SQL API has all the features as mentioned above.
- Create Azure Cosmos DB database
Click Create a resource > Databases > Azure Cosmos DB.
- Create a Cosmos DB account.
- Enter the Account ID
- API as SQL API
- Subscription whatever you have
- Resource Group.
- Location etc
- 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.
We created resources manually over the Azure portal, you can also create them by coding.
Let’s start the coding for creating documents into the ToDoList Collection.
- Create a console application. I have created it in the dot net core 2.0.
- Install NuGet for SQL API into DocumentDbDemo project. So we can connect with the Azure document DB.
- Get the connection string of cosmos DB (we have created earlier ) from the Azure portal.
- Create a 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.
- 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; }
- }
- Let’s come to 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)
- {
-
- 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();
-
- }
-
- 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 created the client of Document DB. It will create a single instance and will reuse or we can say singleton design pattern.
- Next , we will code to create a document into the collection of documentDB.
- var collection = UriFactory.CreateDocumentCollectionUri(configs.docDb.Database, configs.docDb.Collection);
-
-
- Console.WriteLine("\nCreating document");
- JObject emp = new JObject();
- emp.Add("id", "V001");
- emp.Add("name", "virendra");
- emp.Add("address", "Indore");
- emp.Add("Country", "India");
-
- 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,
- Now , we can read that created document by Id
-
- eadResponse = 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,
- Now , we will go for updating the document by changing the value of address property.
-
- 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");
-
- 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.
- Now, we will finally delete that document from the collection.
-
- 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 program.cs class.
- class Program
- {
- private static IConfiguration Configuration { get; set; }
- private static Config configs;
- private DocumentClient client;
- static void Main(string[] args)
- {
-
- 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();
-
- }
-
- private async Task CRUDOperation()
- {
- var collection = UriFactory.CreateDocumentCollectionUri(configs.docDb.Database, configs.docDb.Collection);
- try
- {
-
- Console.WriteLine("\nCreating document");
- JObject emp = new JObject();
- emp.Add("id", "V001");
- emp.Add("name", "virendra");
- emp.Add("address", "Indore");
- emp.Add("Country", "India");
-
- 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)
- {
-
- 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");
-
- 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;
- }
-
- 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());
-
-
-
-
- var deleteResponse = await Client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"));
- Console.WriteLine("Document Deleted");
- Console.ReadKey();
- }
-
-
- 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.