DocumentDB – Data Types

DocumentDB – Data Types ”; Previous Next JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange and also easy for machines to parse and generate. JSON is at the heart of DocumentDB. We transmit JSON over the wire, we store JSON as JSON, and we index the JSON tree allowing queries on the full JSON document. JSON format supports the following data types − S.No. Type & Description 1 Number Double-precision floating-point format in JavaScript 2 String Double-quoted Unicode with backslash escaping 3 Boolean True or false 4 Array An ordered sequence of values 5 Value It can be a string, a number, true or false, null, etc. 6 Object An unordered collection of key:value pairs 7 Whitespace It can be used between any pair of tokens 8 Null Empty Let’s take a look at a simple example DateTime type. Add birth date to the customer class. public class Customer { [JsonProperty(PropertyName = “id”)] public string Id { get; set; } // Must be nullable, unless generating unique values for new customers on client [JsonProperty(PropertyName = “name”)] public string Name { get; set; } [JsonProperty(PropertyName = “address”)] public Address Address { get; set; } [JsonProperty(PropertyName = “birthDate”)] public DateTime BirthDate { get; set; } } We can store, retrieve, and query using DateTime as shown in the following code. private async static Task CreateDocuments(DocumentClient client) { Console.WriteLine(); Console.WriteLine(“**** Create Documents ****”); Console.WriteLine(); var document3Definition = new Customer { Id = “1001”, Name = “Luke Andrew”, Address = new Address { AddressType = “Main Office”, AddressLine1 = “123 Main Street”, Location = new Location { City = “Brooklyn”, StateProvinceName = “New York” }, PostalCode = “11229”, CountryRegionName = “United States” }, BirthDate = DateTime.Parse(DateTime.Today.ToString()), }; Document document3 = await CreateDocument(client, document3Definition); Console.WriteLine(“Created document {0} from typed object”, document3.Id); Console.WriteLine(); } When the above code is compiled and executed, and the document is created, you will see that birth date is added now. **** Create Documents **** Created new document: 1001 { “id”: “1001”, “name”: “Luke Andrew”, “address”: { “addressType”: “Main Office”, “addressLine1”: “123 Main Street”, “location”: { “city”: “Brooklyn”, “stateProvinceName”: “New York” }, “postalCode”: “11229”, “countryRegionName”: “United States” }, “birthDate”: “2015-12-14T00:00:00”, “_rid”: “Ic8LAMEUVgAKAAAAAAAAAA==”, “_ts”: 1450113676, “_self”: “dbs/Ic8LAA==/colls/Ic8LAMEUVgA=/docs/Ic8LAMEUVgAKAAAAAAAAAA==/”, “_etag”: “”00002d00-0000-0000-0000-566efa8c0000″”, “_attachments”: “attachments/” } Created document 1001 from typed object Print Page Previous Next Advertisements ”;

DocumentDB – Limiting Records

DocumentDB – Limiting Records ”; Previous Next Microsoft has recently added a number of improvements on how you can query Azure DocumentDB, such as the TOP keyword to SQL grammar, which made queries run faster and consume fewer resources, increased the limits for query operators, and added support for additional LINQ operators in the .NET SDK. Let’s take a look at a simple example in which we will retrieve only the first two records. If you have a number of records and you want to retrieve only some of them, then you can use the Top keyword. In this example, we have a lot of records of earthquakes. Now we want to show the first two records only Step 1 − Go to the query explorer and run this query. SELECT * FROM c WHERE c.magnitude > 2.5 You will see that it has retrieved four records because we have not specified TOP keyword yet. Step 2 − Now use the TOP keyword with same query. Here we have specified the TOP keyword and ‘2’ means that we want two records only. SELECT TOP 2 * FROM c WHERE c.magnitude > 2.5 Step 3 − Now run this query and you will see that only two records are retrieved. Similarly, you can use TOP keyword in code using .Net SDK. Following is the implementation. private async static Task QueryDocumentsWithPaging(DocumentClient client) { Console.WriteLine(); Console.WriteLine(“**** Query Documents (paged results) ****”); Console.WriteLine(); Console.WriteLine(“Quering for all documents”); var sql = “SELECT TOP 3 * FROM c”; var query = client .CreateDocumentQuery(collection.SelfLink, sql) .AsDocumentQuery(); while (query.HasMoreResults) { var documents = await query.ExecuteNextAsync(); foreach (var document in documents) { Console.WriteLine(” PublicId: {0}; Magnitude: {1};”, document.publicid, document.magnitude); } } Console.WriteLine(); } Following is the CreateDocumentClient task in which are instantiated the DocumentClient and earthquake database. private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { database = client.CreateDatabaseQuery(“SELECT * FROM c WHERE c.id = ”earthquake””).AsEnumerable().First(); collection = client.CreateDocumentCollectionQuery(database.CollectionsLink, “SELECT * FROM c WHERE c.id = ”earthquakedata””).AsEnumerable().First(); await QueryDocumentsWithPaging(client); } } When the above code is compiled and executed, you will see that only three records are retrieved. **** Query Documents (paged results) **** Quering for all documents PublicId: 2015p947400; Magnitude: 2.515176918; PublicId: 2015p947373; Magnitude: 1.506774108; PublicId: 2015p947329; Magnitude: 1.593394461; Print Page Previous Next Advertisements ”;

DocumentDB – Query Document

DocumentDB – Query Document ”; Previous Next In DocumentDB, we actually use SQL to query for documents, so this chapter is all about querying using the special SQL syntax in DocumentDB. Although if you are doing .NET development, there is also a LINQ provider that can be used and which can generate appropriate SQL from a LINQ query. Querying Document using Portal The Azure portal has a Query Explorer that lets you run any SQL query against your DocumentDB database. We will use the Query Explorer to demonstrate the many different capabilities and features of the query language starting with the simplest possible query. Step 1 − In the database blade, click to open the Query Explorer blade. Remember that queries run within the scope of a collection, and so the Query Explorer lets you choose the collection in this dropdown. Step 2 − Select Families collection which is created earlier using the portal. The Query Explorer opens up with this simple query SELECT * FROM c, which simply retrieves all documents from the collection. Step 3 − Execute this query by clicking the ‘Run query’ button. Then you will see that the complete document is retrieved in the Results blade. Querying Document using .Net SDK Following are the steps to run some document queries using .Net SDK. In this example, we want to query for the newly created documents that we just added. Step 1 − Call CreateDocumentQuery, passing in the collection to run the query against by its SelfLink and the query text. private async static Task QueryDocumentsWithPaging(DocumentClient client) { Console.WriteLine(); Console.WriteLine(“**** Query Documents (paged results) ****”); Console.WriteLine(); Console.WriteLine(“Quering for all documents”); var sql = “SELECT * FROM c”; var query = client.CreateDocumentQuery(collection.SelfLink, sql).AsDocumentQuery(); while (query.HasMoreResults) { var documents = await query.ExecuteNextAsync(); foreach (var document in documents) { Console.WriteLine(” Id: {0}; Name: {1};”, document.id, document.name); } } Console.WriteLine(); } This query is also returning all documents in the entire collection, but we”re not calling .ToList on CreateDocumentQuery as before, which would issue as many requests as necessary to pull down all the results in one line of code. Step 2 − Instead, call AsDocumentQuery and this method returns a query object with a HasMoreResults property. Step 3 − If HasMoreResults is true, then call ExecuteNextAsync to get the next chunk and then dump all the contents of that chunk. Step 4 − You can also query using LINQ instead of SQL if you prefer. Here we”ve defined a LINQ query in q, but it won”t execute until we run .ToList on it. private static void QueryDocumentsWithLinq(DocumentClient client) { Console.WriteLine(); Console.WriteLine(“**** Query Documents (LINQ) ****”); Console.WriteLine(); Console.WriteLine(“Quering for US customers (LINQ)”); var q = from d in client.CreateDocumentQuery<Customer>(collection.DocumentsLink) where d.Address.CountryRegionName == ” United States” select new { Id = d.Id, Name = d.Name, City = d.Address.Location.City }; var documents = q.ToList(); Console.WriteLine(“Found {0} UK customers”, documents.Count); foreach (var document in documents) { var d = document as dynamic; Console.WriteLine(” Id: {0}; Name: {1}; City: {2}”, d.Id, d.Name, d.City); } Console.WriteLine(); } The SDK will convert our LINQ query into SQL syntax for DocumentDB, generating a SELECT and WHERE clause based on our LINQ syntax Step 5 − Now call the above queries from the CreateDocumentClient task. private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { database = client.CreateDatabaseQuery(“SELECT * FROM c WHERE c.id = ”myfirstdb””).AsEnumerable().First(); collection = client.CreateDocumentCollectionQuery(database.CollectionsLink, “SELECT * FROM c WHERE c.id = ”MyCollection””).AsEnumerable().First(); //await CreateDocuments(client); await QueryDocumentsWithPaging(client); QueryDocumentsWithLinq(client); } } When the above code is executed, you will receive the following output. **** Query Documents (paged results) **** Quering for all documents Id: 7e9ad4fa-c432-4d1a-b120-58fd7113609f; Name: New Customer 1; Id: 34e9873a-94c8-4720-9146-d63fb7840fad; Name: New Customer 1; **** Query Documents (LINQ) **** Quering for US customers (LINQ) Found 2 UK customers Id: 7e9ad4fa-c432-4d1a-b120-58fd7113609f; Name: New Customer 1; City: Brooklyn Id: 34e9873a-94c8-4720-9146-d63fb7840fad; Name: New Customer 1; City: Brooklyn Print Page Previous Next Advertisements ”;

DocumentDB – Delete Collection

DocumentDB – Delete Collection ”; Previous Next To drop collection or collections you can do the same from the portal as well as from the code by using .Net SDK. Step 1 − Go to your DocumentDB account on Azure portal. For the purpose of demo, I have added two more collections as seen in the following screenshot. Step 2 − To drop any collection, you need to click on that collection. Let’s select TempCollection1. You will see the following page, select the ‘Delete Collection’ option. Step 3 − It will display the confirmation message. Now click ‘Yes’ button. You will see that the TempCollection1 is no more available on your dashboard. You can also delete collections from your code using .Net SDK. To do that, following are the following steps. Step 1 − Let”s delete the collection by specifying the ID of the collection we want to delete. It”s the usual pattern of querying by Id to obtain the selfLinks needed to delete a resource. private async static Task DeleteCollection(DocumentClient client, string collectionId) { Console.WriteLine(); Console.WriteLine(“**** Delete Collection {0} in {1} ****”, collectionId, database.Id); var query = new SqlQuerySpec { QueryText = “SELECT * FROM c WHERE c.id = @id”, Parameters = new SqlParameterCollection { new SqlParameter { Name = “@id”, Value = collectionId } } }; DocumentCollection collection = client.CreateDocumentCollectionQuery(database.SelfLink, query).AsEnumerable().First(); await client.DeleteDocumentCollectionAsync(collection.SelfLink); Console.WriteLine(“Deleted collection {0} from database {1}”, collectionId, database.Id); } Here we see the preferred way of constructing a parameterized query. We”re not hardcoding the collectionId so this method can be used to delete any collection. We are querying for a specific collection by Id where the Id parameter is defined in this SqlParameterCollection assigned to the parameter”s property of this SqlQuerySpec. Then the SDK does the work of constructing the final query string for DocumentDB with the collectionId embedded inside of it. Step 2 − Run the query and then use its SelfLink to delete the collection from the CreateDocumentClient task. private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { database = client.CreateDatabaseQuery(“SELECT * FROM c WHERE c.id = ”myfirstdb””).AsEnumerable().First(); await DeleteCollection(client, “TempCollection”); } } Following is the complete implementation of Program.cs file. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.Documents.Linq; using Newtonsoft.Json; namespace DocumentDBDemo { class Program { private const string EndpointUrl = “https://azuredocdbdemo.documents.azure.com:443/”; private const string AuthorizationKey = “BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/ StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==”; private static Database database; static void Main(string[] args) { try { CreateDocumentClient().Wait(); } catch (Exception e) { Exception baseException = e.GetBaseException(); Console.WriteLine(“Error: {0}, Message: {1}”, e.Message, baseException.Message); } Console.ReadKey(); } private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { database = client.CreateDatabaseQuery(“SELECT * FROM c WHERE c.id = ”myfirstdb””).AsEnumerable().First(); await DeleteCollection(client, “TempCollection”); //await CreateCollection(client, “MyCollection1”); //await CreateCollection(client, “MyCollection2”, “S2”); ////await CreateDatabase(client); //GetDatabases(client); //await DeleteDatabase(client); //GetDatabases(client); } } private async static Task CreateCollection(DocumentClient client, string collectionId, string offerType = “S1”) { Console.WriteLine(); Console.WriteLine(“**** Create Collection {0} in {1} ****”, collectionId, database.Id); var collectionDefinition = new DocumentCollection { Id = collectionId }; var options = new RequestOptions { OfferType = offerType }; var result = await client.CreateDocumentCollectionAsync(database.SelfLink, collectionDefinition, options); var collection = result.Resource; Console.WriteLine(“Created new collection”); ViewCollection(collection); } private static void ViewCollection(DocumentCollection collection) { Console.WriteLine(“Collection ID: {0} “, collection.Id); Console.WriteLine(“Resource ID: {0} “, collection.ResourceId); Console.WriteLine(“Self Link: {0} “, collection.SelfLink); Console.WriteLine(“Documents Link: {0} “, collection.DocumentsLink); Console.WriteLine(“UDFs Link: {0} “, collection.UserDefinedFunctionsLink); Console.WriteLine(“StoredProcs Link: {0} “, collection.StoredProceduresLink); Console.WriteLine(“Triggers Link: {0} “, collection.TriggersLink); Console.WriteLine(“Timestamp: {0} “, collection.Timestamp); } private async static Task DeleteCollection(DocumentClient client, string collectionId) { Console.WriteLine(); Console.WriteLine(“**** Delete Collection {0} in {1} ****”, collectionId, database.Id); var query = new SqlQuerySpec { QueryText = “SELECT * FROM c WHERE c.id = @id”, Parameters = new SqlParameterCollection { new SqlParameter { Name = “@id”, Value = collectionId } } }; DocumentCollection collection = client.CreateDocumentCollectionQuery (database.SelfLink, query).AsEnumerable().First(); await client.DeleteDocumentCollectionAsync(collection.SelfLink); Console.WriteLine(“Deleted collection {0} from database {1}”, collectionId, database.Id); } } } When the above code is compiled and executed, you will receive the following output. **** Delete Collection TempCollection in myfirstdb **** Deleted collection TempCollection from database myfirstdb Print Page Previous Next Advertisements ”;

DocumentDB – Insert Document

DocumentDB – Insert Document ”; Previous Next In this chapter, we will get to work with actual documents in a collection. You can create documents using either Azure portal or .Net SDK. Creating Documents with the Azure Portal Let’s take a look at the following steps to add document to your collection. Step 1 − Add new collection Families of S1 pricing tier in myfirstdb. Step 2 − Select the Families collection and click on Create Document option to open the New Document blade. This is just a simple text editor that lets you type any JSON for a new document. Step 3 − As this is raw data entry, let’s enter our first document. { “id”: “AndersenFamily”, “lastName”: “Andersen”, “parents”: [ { “firstName”: “Thomas”, “relationship”: “father” }, { “firstName”: “Mary Kay”, “relationship”: “mother” } ], “children”: [ { “firstName”: “Henriette Thaulow”, “gender”: “female”, “grade”: 5, “pets”: [ { “givenName”: “Fluffy”, “type”: “Rabbit” } ] } ], “location”: { “state”: “WA”, “county”: “King”, “city”: “Seattle”}, “isRegistered”: true } When you enter the above document, you will see the following screen. Notice that we”ve supplied an id for the document. The id value is always required, and it must be unique across all other documents in the same collection. When you leave it out then DocumentDB would automatically generate one for you using a GUID or a Globally Unique Identifier. The id is always a string and it can”t be a number, date, Boolean, or another object, and it can”t be longer than 255 characters. Also notice the document”s hierarchal structure which has a few top-level properties like the required id, as well as lastName and isRegistered, but it also has nested properties. For instance, the parents property is supplied as a JSON array as denoted by the square brackets. We also have another array for children, even though there”s only one child in the array in this example. Step 4 − Click ‘Save’ button to save the document and we”ve created our first document. As you can see that pretty formatting was applied to our JSON, which breaks up every property on its own line indented with a whitespace to convey the nesting level of each property. The portal includes a Document Explorer, so let”s use that now to retrieve the document we just created. Step 5 − Choose a database and any collection within the database to view the documents in that collection. We currently have just one database named myfirstdb with one collection called Families, both of which have been preselected here in the dropdowns. By default, the Document Explorer displays an unfiltered list of documents within the collection, but you can also search for any specific document by ID or multiple documents based on a wildcard search of a partial ID. We have only one document in our collection so far, and we see its ID on the following screen, AndersonFamily. Step 6 − Click on the ID to view the document. Creating Documents with the .NET SDK As you know that documents are just another type of resource and you”ve already become familiar with how to treat resources using the SDK. The one big difference between documents and other resources is that, of course, they”re schema free. Thus there are a lot of options. Naturally, you can just work JSON object graphs or even raw strings of JSON text, but you can also use dynamic objects that lets you bind to properties at runtime without defining a class at compile time. You can also work with real C# objects, or Entities as they are called, which might be your business domain classes. Let’s start to create documents using .Net SDK. Following are the steps. Step 1 − Instantiate DocumentClient then we will query for the myfirstdb database and then query for the MyCollection collection, which we store in this private variable collection so that it”s accessible throughout the class. private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { database = client.CreateDatabaseQuery(“SELECT * FROM c WHERE c.id = ”myfirstdb””).AsEnumerable().First(); collection = client.CreateDocumentCollectionQuery(database.CollectionsLink, “SELECT * FROM c WHERE c.id = ”MyCollection””).AsEnumerable().First(); await CreateDocuments(client); } } Step 2 − Create some documents in CreateDocuments task. private async static Task CreateDocuments(DocumentClient client) { Console.WriteLine(); Console.WriteLine(“**** Create Documents ****”); Console.WriteLine(); dynamic document1Definition = new { name = “New Customer 1”, address = new { addressType = “Main Office”, addressLine1 = “123 Main Street”, location = new { city = “Brooklyn”, stateProvinceName = “New York” }, postalCode = “11229”, countryRegionName = “United States” }, }; Document document1 = await CreateDocument(client, document1Definition); Console.WriteLine(“Created document {0} from dynamic object”, document1.Id); Console.WriteLine(); } The first document will be generated from this dynamic object. This might look like JSON, but of course it isn”t. This is C# code and we”re creating a real .NET object, but there”s no class definition. Instead, the properties are inferred from the way the object is initialized. Notice that we haven”t supplied an Id property for this document. Now let”s have a look into CreateDocument. It looks like the same pattern we saw for creating databases and collections. private async static Task<Document> CreateDocument(DocumentClient client, object documentObject) { var result = await client.CreateDocumentAsync(collection.SelfLink, documentObject); var document = result.Resource; Console.WriteLine(“Created new document: {0}rn{1}”, document.Id, document); return result; } Step 3 − This time we call CreateDocumentAsync specifying the SelfLink of the collection we want to add the document to. We get back a response with a resource property that, in this case, represents the new document with its system-generated properties. The Document object is a defined class in the SDK that inherits from resource and so it has all the common resource properties, but it also includes the dynamic properties that define the schema-free document itself. private async static Task CreateDocuments(DocumentClient client) { Console.WriteLine(); Console.WriteLine(“**** Create Documents ****”); Console.WriteLine(); dynamic document1Definition = new { name = “New Customer 1”, address = new { addressType =

DocumentDB – Delete Document

DocumentDB – Delete Document ”; Previous Next In this chapter, we will learn how to delete a document from your DocumentDB account. Using Azure Portal, you can easily delete any document by opening the document in Document Explorer and click the ‘Delete’ option. It will display the confirmation message. Now press the Yes button and you will see that the document is no longer available in your DocumentDB account. Now when you want to delete a document using .Net SDK. Step 1 − It”s the same pattern as we”ve seen before where we”ll query first to get the SelfLinks of each new document. We don”t use SELECT * here, which would return the documents in their entirety, which we don”t need. Step 2 − Instead we”re just selecting the SelfLinks into a list and then we just call DeleteDocumentAsync for each SelfLink, one at a time, to delete the documents from the collection. private async static Task DeleteDocuments(DocumentClient client) { Console.WriteLine(); Console.WriteLine(“>>> Delete Documents <<<“); Console.WriteLine(); Console.WriteLine(“Quering for documents to be deleted”); var sql = “SELECT VALUE c._self FROM c WHERE STARTSWITH(c.name, ”New Customer”) = true”; var documentLinks = client.CreateDocumentQuery<string>(collection.SelfLink, sql).ToList(); Console.WriteLine(“Found {0} documents to be deleted”, documentLinks.Count); foreach (var documentLink in documentLinks) { await client.DeleteDocumentAsync(documentLink); } Console.WriteLine(“Deleted {0} new customer documents”, documentLinks.Count); Console.WriteLine(); } Step 3 − Now let’s call the above DeleteDocuments from the CreateDocumentClient task. private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { database = client.CreateDatabaseQuery(“SELECT * FROM c WHERE c.id = ”myfirstdb””).AsEnumerable().First(); collection = client.CreateDocumentCollectionQuery(database.CollectionsLink, “SELECT * FROM c WHERE c.id = ”MyCollection””).AsEnumerable().First(); await DeleteDocuments(client); } } When the above code is executed, you will receive the following output. ***** Delete Documents ***** Quering for documents to be deleted Found 2 documents to be deleted Deleted 2 new customer documents Print Page Previous Next Advertisements ”;

DocumentDB – Update Document

DocumentDB – Update Document ”; Previous Next In this chapter, we will learn how to update the documents. Using Azure portal, you can easily update document by opening the document in Document explorer and updating it in editor like a text file. Click ‘Save’ button. Now when you need to change a document using .Net SDK you can just replace it. You don”t need to delete and recreate it, which besides being tedious, would also change the resource id, which you wouldn”t want to do when you”re just modifying a document. Here are the following steps to update the document using .Net SDK. Let’s take a look at the following ReplaceDocuments task where we will query for documents where the isNew property is true, but we will get none because there aren”t any. So, let”s modify the documents we added earlier, those whose names start with New Customer. Step 1 − Add the isNew property to these documents and set its value to true. private async static Task ReplaceDocuments(DocumentClient client) { Console.WriteLine(); Console.WriteLine(“>>> Replace Documents <<<“); Console.WriteLine(); Console.WriteLine(“Quering for documents with ”isNew” flag”); var sql = “SELECT * FROM c WHERE c.isNew = true”; var documents = client.CreateDocumentQuery(collection.SelfLink, sql).ToList(); Console.WriteLine(“Documents with ”isNew” flag: {0} “, documents.Count); Console.WriteLine(); Console.WriteLine(“Quering for documents to be updated”); sql = “SELECT * FROM c WHERE STARTSWITH(c.name, ”New Customer”) = true”; documents = client.CreateDocumentQuery(collection.SelfLink, sql).ToList(); Console.WriteLine(“Found {0} documents to be updated”, documents.Count); foreach (var document in documents) { document.isNew = true; var result = await client.ReplaceDocumentAsync(document._self, document); var updatedDocument = result.Resource; Console.WriteLine(“Updated document ”isNew” flag: {0}”, updatedDocument.isNew); } Console.WriteLine(); Console.WriteLine(“Quering for documents with ”isNew” flag”); sql = “SELECT * FROM c WHERE c.isNew = true”; documents = client.CreateDocumentQuery(collection.SelfLink, sql).ToList(); Console.WriteLine(“Documents with ”isNew” flag: {0}: “, documents.Count); Console.WriteLine(); } Step 2 − Get the documents to be updated using the same STARTSWITH query and that gives us the documents, which we are getting back here as dynamic objects. Step 3 − Attach the isNew property and set it to true for each document. Step 4 − Call ReplaceDocumentAsync, passing in the document”s SelfLink, along with the updated document. Now just to prove that this worked, query for documents where isNew equaled true. Let’s call the above queries from the CreateDocumentClient task. private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { database = client.CreateDatabaseQuery(“SELECT * FROM c WHERE c.id = ”myfirstdb””).AsEnumerable().First(); collection = client.CreateDocumentCollectionQuery(database.CollectionsLink, “SELECT * FROM c WHERE c.id = ”MyCollection””).AsEnumerable().First(); //await CreateDocuments(client); //QueryDocumentsWithSql(client); //await QueryDocumentsWithPaging(client); //QueryDocumentsWithLinq(client); await ReplaceDocuments(client); } } When the above code is compiled and executed, you will receive the following output. **** Replace Documents **** Quering for documents with ”isNew” flag Documents with ”isNew” flag: 0 Quering for documents to be updated Found 2 documents to be updated Updated document ‘isNew’ flag: True Updated document ‘isNew’ flag: True Quering for documents with ”isNew” flag Documents with ”isNew” flag: 2 Print Page Previous Next Advertisements ”;

DocumentDB – Advantages

DocumentDB – Advantages ”; Previous Next DocumentDB stands out with some very unique capabilities. Azure DocumentDB offers the following key capabilities and benefits. Schema Free In a relational database, every table has a schema that defines the columns and data types that each row in the table must conform to. In contrast, a document database has no defined schema, and every document can be structured differently. SQL Syntax DocumentDB enables complex ad-hoc queries using SQL language, and every document is instantly queryable the moment it”s created. You can search on any property anywhere within the document hierarchy. Tunable Consistency It provides some granular, well-defined consistency levels, which allows you to make sound trade-offs between consistency, availability, and latency. You can select from four well-defined consistency levels to achieve optimal trade-off between consistency and performance. For queries and read operations, DocumentDB offers four distinct consistency levels − Strong Bounded-staleness Session Eventual Elastic Scale Scalability is the name of the game with NoSQL, and DocumentDB delivers. DocumentDB has already been proven its scale. Major services like Office OneNote and Xbox are already backed by DocumentDB with databases containing tens of terabytes of JSON documents, over a million active users, and operating consistently with 99.95% availability. You can elastically scale DocumentDB with predictable performance by creating more units as your application grows. Fully Managed DocumentDB is available as a fully managed cloud-based platform as a service running on Azure. There is simply nothing for you to install or manage. There are no servers, cables, no operating systems or updates to deal with, no replicas to set up. Microsoft does all that work and keeps the service running. Within literally minutes, you can get started working with DocumentDB using just a browser and an Azure subscription. Print Page Previous Next Advertisements ”;

DocumentDB – Create Database

DocumentDB – Create Database ”; Previous Next In this chapter, we will learn how to create a database. To use Microsoft Azure DocumentDB, you must have a DocumentDB account, a database, a collection, and documents. We already have a DocumentDB account, now to create database we have two options − Microsoft Azure Portal or .Net SDK Create a Database for DocumentDB using the Microsoft Azure Portal To create a database using portal, following are the steps. Step 1 − Login to Azure portal and you will see the dashboard. Step 2 − Now click on the created DocumentDB account and you will see the details as shown in the following screenshot. Step 3 − Select the Add Database option and provide the ID for your database. Step 4 − Click OK. You can see that the database is added. At the moment, it has no collection, but we can add collections later which are the containers that will store our JSON documents. Notice that it has both an ID and a Resource ID. Create a Database for DocumentDB Using .Net SDK To create a database using .Net SDK, following are the steps. Step 1 − Open the Console Application in Visual Studio from the last chapter. Step 2 − Create the new database by creating a new database object. To create a new database, we only need to assign the Id property, which we are setting to “mynewdb” in a CreateDatabase task. private async static Task CreateDatabase(DocumentClient client) { Console.WriteLine(); Console.WriteLine(“******** Create Database *******”); var databaseDefinition = new Database { Id = “mynewdb” }; var result = await client.CreateDatabaseAsync(databaseDefinition); var database = result.Resource; Console.WriteLine(” Database Id: {0}; Rid: {1}”, database.Id, database.ResourceId); Console.WriteLine(“******** Database Created *******”); } Step 3 − Now pass this databaseDefinition on to CreateDatabaseAsync, and get back a result with a Resource property. All the create object methods return a Resource property that describes the item that was created, which is a database in this case. We get the new database object from the Resource property and it is displayed on the Console along with the Resource ID that DocumentDB assigned to it. Step 4 − Now call CreateDatabase task from the CreateDocumentClient task after DocumentClient is instantiated. using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { await CreateDatabase(client); } Following is the complete Program.cs file so far. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.Documents.Linq; using Newtonsoft.Json; namespace DocumentDBDemo { class Program { private const string EndpointUrl = “https://azuredocdbdemo.documents.azure.com:443/”; private const string AuthorizationKey = “BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/ StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==”; static void Main(string[] args) { try { CreateDocumentClient().Wait(); } catch (Exception e) { Exception baseException = e.GetBaseException(); Console.WriteLine(“Error: {0}, Message: {1}”, e.Message, baseException.Message); } Console.ReadKey(); } private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { await CreateDatabase(client); } } private async static Task CreateDatabase(DocumentClient client) { Console.WriteLine(); Console.WriteLine(“******** Create Database *******”); var databaseDefinition = new Database { Id = “mynewdb” }; var result = await client.CreateDatabaseAsync(databaseDefinition); var database = result.Resource; Console.WriteLine(” Database Id: {0}; Rid: {1}”, database.Id, database.ResourceId); Console.WriteLine(“******** Database Created *******”); } } } When the above code is compiled and executed, you will receive the following output which contains the Database and Resources IDs. ******** Create Database ******* Database Id: mynewdb; Rid: ltpJAA== ******** Database Created ******* Print Page Previous Next Advertisements ”;

DocumentDB – Create Account

DocumentDB – Create Account ”; Previous Next To use Microsoft Azure DocumentDB, you must create a DocumentDB account. In this chapter, we will create a DocumentDB account using Azure portal. Step 1 − Log in to the online https://portal.azure.com if you already have an Azure subscription otherwise you need to sign in first. You will see the main Dashboard. It is fully customizable so you can arrange these tiles any way you like, resize them, add and remove tiles for things you frequently use or no longer do. Step 2 − Select the ‘New’ option on the top left side of the page. Step 3 − Now select Data &plus; Storage > Azure DocumentDB option and you see the following New DocumentDB account section. We need to come up with a globally unique name (ID), which combined with .documents.azure.com is the publicly addressable endpoint to our DocumentDB account. All the databases we create beneath that account can be accessed over the internet using this endpoint. Step 4 − Let’s name it azuredocdbdemo and click on Resource Group → new_resource. Step 5 − Choose the location i.e., which Microsoft data center you want this account to be hosted. Select the location and choose your region. Step 6 − Check Pin to dashboard checkbox and just go ahead and click Create button. You can see that the tile has already been added to the Dashboard, and it”s letting us know that the account is being created. It can actually take a few minutes to set things up for a new account while DocumentDB allocates the endpoint, provisions replicas, and performs other work in the background. Once it is done, you will see the dashboard. Step 7 − Now click on the created DocumentDB account and you will see a detailed screen as the following image. Print Page Previous Next Advertisements ”;