DocumentDB – Useful Resources

DocumentDB – Useful Resources ”; Previous Next The following resources contain additional information on DocumentDB. Please use them to get more in-depth knowledge on this topic. Useful Links on DocumentDB DocumentDB − Reference for DocumentDB. Introduction − Introduction Reference for DocumentDB. DocumentDB Wiki − Wikipedia Reference for DocumentDB. Useful Books on DocumentDB To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;

DocumentDB – Discussion

Discuss DocumentDB ”; Previous Next DocumentDB is Microsoft”s newest NoSQL document database platform that runs on Azure. DocumentDB is designed keeping in mind the requirements of managing data for latest applications. This tutorial explains the basics of DocumentDB with illustrative examples. Print Page Previous Next Advertisements ”;

DocumentDB – Visualize Data

DocumentDB – Visualize Data ”; Previous Next In this chapter, we will learn how to visualize data which is stored in DocumentDB. Microsoft provided Power BI Desktop tool which transforms your data into rich visuals. It also enables you to retrieve data from various data sources, merge and transform the data, create powerful reports and visualizations, and publish the reports to Power BI. In the latest version of Power BI Desktop, Microsoft has added support for DocumentDB as well in which you can now connect to your DocumentDB account. You can download this tool from the link, https://powerbi.microsoft.com Let’s take a look at an example in which we will visualize the earthquakes data imported in the last chapter. Step 1 − Once the tool is downloaded, launch the Power BI desktop. Step 2 − Click ‘Get Data’ option which is on the Home tab under External Data group and it will display the Get Data page. Step 3 − Select the Microsoft Azure DocumentDB (Beta) option and click ‘Connect’ button. Step 4 − Enter the URL of your Azure DocumentDB account, Database and Collection from which you want visualize data and press Ok. If you are connecting to this endpoint for the first time, you will be prompted for the account key. Step 5 − Enter the account key (primary key) which is unique for each DocumentDB account available on Azure portal, and then click Connect. When the account is successfully connected, it will retrieve the data from specified database. The Preview pane shows a list of Record items, a Document is represented as a Record type in Power BI. Step 6 − Click ‘Edit’ button which will launch the Query Editor. Step 7 − In the Power BI Query Editor, you should see a Document column in the center pane, click on the expander at the right side of the Document column header and select the columns which you want display. As you can see that we have latitude and longitude as separate column but we visualize data in latitude, longitude coordinates form. Step 8 − To do that, click ‘Add Column’ tab. Step 9 − Select the Add Custom Column which will display the following page. Step 10 − Specify the new column name, let’s say LatLong and also the formula which will combine the latitude and longitude in one column separated by a comma. Following is the formula. Text.From([latitude])&”, “&Text.From([longitude]) Step 11 − Click OK to continue and you will see that the new column is added. Step 12 − Go to the Home tab and click ‘Close & Apply’ option. Step 13 − You can create reports by dragging and dropping fields into the Report canvas. You can see on the right, there are two panes − one Visualizations pane and the other is Fields pane. Let’s create a map view showing the location of each earthquake. Step 14 − Drag the map visual type from the Visualizations pane. Step 15 − Now, drag and drop the LatLong field from the Fields pane to the Location property in Visualizations pane. Then, drag and drop the magnitude field to the Values property. Step 16 − Drag and drop the depth field to the Color saturation property. You will now see the Map visual showing a set of bubbles indicating the location of each earthquake. Print Page Previous Next Advertisements ”;

DocumentDB – Geospatial Data

DocumentDB – Geospatial Data ”; Previous Next Microsoft added geospatial support, which lets you store location data in your documents and perform spatial calculations for distance and intersections between points and polygons. Spatial data describes the position and shape of objects in space. Typically, it can be used to represent the location of a person, a place of interest, or the boundary of a city, or a lake. Common use cases often involve proximity queries. For e.g., “find all universities near my current location”. A Point denotes a single position in space which represents the exact location, e.g. street address of particular university. A point is represented in DocumentDB using its coordinate pair (longitude and latitude). Following is an example of JSON point. { “type”:”Point”, “coordinates”:[ 28.3, -10.7 ] } Let’s take a look at a simple example which contains the location of a university. { “id”:”case-university”, “name”:”CASE: Center For Advanced Studies In Engineering”, “city”:”Islamabad”, “location”: { “type”:”Point”, “coordinates”:[ 33.7194136, -73.0964862 ] } } To retrieve the university name based on the location, you can use the following query. SELECT c.name FROM c WHERE c.id = “case-university” AND ST_ISVALID({ “type”:”Point”, “coordinates”:[ 33.7194136, -73.0964862 ] }) When the above query is executed you will receive the following output. [ { “name”: “CASE: Center For Advanced Studies In Engineering” } ] Create Document with Geospatial Data in .NET You can create a document with geospatial data, let’s take a look at a simple example in which a university document is created. private async static Task CreateDocuments(DocumentClient client) { Console.WriteLine(); Console.WriteLine(“**** Create Documents ****”); Console.WriteLine(); var uniDocument = new UniversityProfile { Id = “nust”, Name = “National University of Sciences and Technology”, City = “Islamabad”, Loc = new Point(33.6455715, 72.9903447) }; Document document = await CreateDocument(client, uniDocument); Console.WriteLine(“Created document {0} from typed object”, document.Id); Console.WriteLine(); } Following is the implementation for the UniversityProfile class. public class UniversityProfile { [JsonProperty(PropertyName = “id”)] public string Id { get; set; } [JsonProperty(“name”)] public string Name { get; set; } [JsonProperty(“city”)] public string City { get; set; } [JsonProperty(“location”)] public Point Loc { get; set; } } When the above code is compiled and executed, you will receive the following output. **** Create Documents **** Created new document: nust { “id”: “nust”, “name”: “National University of Sciences and Technology”, “city”: “Islamabad”, “location”: { “type”: “Point”, “coordinates”: [ 33.6455715, 72.9903447 ] }, “_rid”: “Ic8LAMEUVgANAAAAAAAAAA==”, “_ts”: 1450200910, “_self”: “dbs/Ic8LAA==/colls/Ic8LAMEUVgA=/docs/Ic8LAMEUVgANAAAAAAAAAA==/”, “_etag”: “”00004100-0000-0000-0000-56704f4e0000″”, “_attachments”: “attachments/” } Created document nust from typed object Print Page Previous Next Advertisements ”;

DocumentDB – Data Migration

DocumentDB – Data Migration ”; Previous Next With the DocumentDB Data Migration tool, you can easily migrate data to DocumentDB. The DocumentDB Data Migration Tool is a free and open source utility you can download from the Microsoft Download Center https://www.microsoft.com/ The Migration Tool supports many data sources, some of them are listed below − SQL Server JSON files Flat files of Comma-separated Values (CSV) MongoDB Azure Table Storage Amazon DynamoDB HBase, and even other DocumentDB databases After downloading the DocumentDB Data Migration tool, extract the zip file. You can see two executables in this folder as shown in the following screenshot. First, there is dt.exe, which is the console version with a command line interface, and then there is dtui.exe, which is the desktop version with a graphical user interface. Let”s launch the GUI version. You can see the Welcome page. Click ‘Next’ for the Source Information page. Here”s where you configure your data source, and you can see the many supported choices from the dropdown menu. When you make a selection, the rest of the Source Information page changes accordingly. It is very easy to import data to DocumentDB using the DocumentDB Data Migration Tool. We recommend you exercise the above examples and use the other data files as well. Print Page Previous Next Advertisements ”;

DocumentDB – Quick Guide

DocumentDB – Quick Guide ”; Previous Next DocumentDB – Introduction In this chapter, we will briefly discuss the major concepts around NoSQL and document databases. We will also have a quick overview of DocumentDB. NoSQL Document Database DocumentDB is Microsoft”s newest NoSQL document database, so when you say NoSQL document database then, what precisely do we mean by NoSQL, and document database? SQL means Structured Query Language which is traditional query language of relational databases. SQL is often equated with relational databases. It”s really more helpful to think of a NoSQL database as a non-relational database, so NoSQL really means non-relational. There are different types of NoSQL databases which include key value stores such as − Azure Table Storage. Column-based stores like Cassandra. Graph databases like NEO4. Document databases like MongoDB and Azure DocumentDB. Azure DocumentDB Microsoft officially launched Azure DocumentDB on April 8th, 2015, and it certainly can be characterized as a typical NoSQL document database. It”s massively scalable, and it works with schema-free JSON documents. DocumentDB is a true schema-free NoSQL document database service designed for modern mobile and web applications. It also delivers consistently fast reads and writes, schema flexibility, and the ability to easily scale a database up and down on demand. It does not assume or require any schema for the JSON documents it indexes. DocumentDB automatically indexes every property in a document as soon as the document is added to the database. DocumentDB enables complex ad-hoc queries using a SQL language, and every document is instantly queryable the moment it”s created, and you can search on any property anywhere within the document hierarchy. DocumentDB – Pricing DocumentDB is billed based on the number of collections contained in a database account. Each account can have one or more databases and each database can have a virtually unlimited number of collections, although there is an initial default quota of 100. This quota can be lifted by contacting Azure support. A collection is not only a unit of scale, but also a unit of cost, so in DocumentDB you pay per collection, which has a storage capacity of up to 10 GB. At a minimum, you”ll need one S1 collection to store documents in a database that will cost roughly $25 per month, which gets billed against your Azure subscription. As your database grows in size and exceeds 10 GB, you”ll need to purchase another collection to contain the additional data. Each S1 collection will give you 250 request units per second, and if that”s not enough, then you can scale the collection up to an S2 and get a 1000 request units per second for about $50 a month. You can also turn it all the way up to an S3 and pay around $100 a month. DocumentDB – Advantages 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. DocumentDB – Environment Setup Microsoft provides a free version of Visual Studio which also contains SQL Server and it can be downloaded from https://www.visualstudio.com Installation Step 1 − Once downloading is completed, run the installer. The following dialog will be displayed. Step 2 − Click on the Install button and it will start the installation process. Step 3 − Once the installation process is completed successfully, you will see the following dialog. Step 4 − Close this dialog and restart your computer if required. Step 5 − Now open Visual studio from start Menu which will open the below dialog. It will take some time for the first time only for preparation. Once all is done, you will see the main window of Visual Studio. Step 6 − Let’s create a new project from File → New → Project. Step 7 − Select Console Application, enter DocumentDBDemo in the Name field and click OK button. Step 8 − In solution Explorer, right-click on your project. Step 9 − Select Manage NuGet Packages which will open the following window in Visual Studio and in the Search Online input box, search for DocumentDB Client Library. Step 10 − Install the latest version by clicking the install button. Step 11 − Click “I Accept”. Once installation is done you will see the message in your output window. You are now ready to start your application. DocumentDB – Create Account To use Microsoft Azure DocumentDB, you must create a DocumentDB

DocumentDB – Access Control

DocumentDB – Access Control ”; Previous Next DocumentDB provides the concepts to control access to DocumentDB resources. Access to DocumentDB resources is governed by a master key token or a resource token. Connections based on resource tokens can only access the resources specified by the tokens and no other resources. Resource tokens are based on user permissions. First you create one or more users, and these are defined at the database level. Then you create one or more permissions for each user, based on the resources that you want to allow each user to access. Each permission generates a resource token that allows either read-only or full access to a given resource and that can be any user resource within the database. Users are defined at the database level and permissions are defined for each user. Users and permissions apply to all collections in the database. Let’s take a look at a simple example in which we will learn how to define users and permissions to achieve granular security in DocumentDB. We will start with a new DocumentClient and query for the myfirstdb 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 = ”myfirstdb””).AsEnumerable().First(); collection = client.CreateDocumentCollectionQuery(database.CollectionsLink, “SELECT * FROM c WHERE c.id = ”MyCollection””).AsEnumerable().First(); var alice = await CreateUser(client, “Alice”); var tom = await CreateUser(client, “Tom”); } } Following is the implementation for CreateUser. private async static Task<User> CreateUser(DocumentClient client, string userId) { Console.WriteLine(); Console.WriteLine(“**** Create User {0} in {1} ****”, userId, database.Id); var userDefinition = new User { Id = userId }; var result = await client.CreateUserAsync(database.SelfLink, userDefinition); var user = result.Resource; Console.WriteLine(“Created new user”); ViewUser(user); return user; } Step 1 − Create two users, Alice and Tom like any resource we create, we construct a definition object with the desired Id and call the create method and in this case we”re calling CreateUserAsync with the database”s SelfLink and the userDefinition. We get back the result from whose resource property we obtain the newly created user object. Now to see these two new users in the database. private static void ViewUsers(DocumentClient client) { Console.WriteLine(); Console.WriteLine(“**** View Users in {0} ****”, database.Id); var users = client.CreateUserQuery(database.UsersLink).ToList(); var i = 0; foreach (var user in users) { i++; Console.WriteLine(); Console.WriteLine(“User #{0}”, i); ViewUser(user); } Console.WriteLine(); Console.WriteLine(“Total users in database {0}: {1}”, database.Id, users.Count); } private static void ViewUser(User user) { Console.WriteLine(“User ID: {0} “, user.Id); Console.WriteLine(“Resource ID: {0} “, user.ResourceId); Console.WriteLine(“Self Link: {0} “, user.SelfLink); Console.WriteLine(“Permissions Link: {0} “, user.PermissionsLink); Console.WriteLine(“Timestamp: {0} “, user.Timestamp); } Step 2 − Call CreateUserQuery, against the database”s UsersLink to retrieve a list of all users. Then loop through them and view their properties. Now we have to create them first. So let”s say that we wanted to allow Alice read/write permissions to the MyCollection collection, but Tom can only read documents in the collection. await CreatePermission(client, alice, “Alice Collection Access”, PermissionMode.All, collection); await CreatePermission(client, tom, “Tom Collection Access”, PermissionMode.Read, collection); Step 3− Create a permission on a resource that is MyCollection collection so we need to get that resource a SelfLink. Step 4 − Then create a Permission.All on this collection for Alice and a Permission.Read on this collection for Tom. Following is the implementation for CreatePermission. private async static Task CreatePermission(DocumentClient client, User user, string permId, PermissionMode permissionMode, string resourceLink) { Console.WriteLine(); Console.WriteLine(“**** Create Permission {0} for {1} ****”, permId, user.Id); var permDefinition = new Permission { Id = permId, PermissionMode = permissionMode, ResourceLink = resourceLink }; var result = await client.CreatePermissionAsync(user.SelfLink, permDefinition); var perm = result.Resource; Console.WriteLine(“Created new permission”); ViewPermission(perm); } As you should come to expect by now, we do this by creating a definition object for the new permission, which includes an Id and a permissionMode, which is either Permission.All or Permission.Read, and the SelfLink of the resource that”s being secured by the permission. Step 5 − Call CreatePermissionAsync and get the created permission from the resource property in the result. To view the created permission, following is the implementation of ViewPermissions. private static void ViewPermissions(DocumentClient client, User user) { Console.WriteLine(); Console.WriteLine(“**** View Permissions for {0} ****”, user.Id); var perms = client.CreatePermissionQuery(user.PermissionsLink).ToList(); var i = 0; foreach (var perm in perms) { i++; Console.WriteLine(); Console.WriteLine(“Permission #{0}”, i); ViewPermission(perm); } Console.WriteLine(); Console.WriteLine(“Total permissions for {0}: {1}”, user.Id, perms.Count); } private static void ViewPermission(Permission perm) { Console.WriteLine(“Permission ID: {0} “, perm.Id); Console.WriteLine(“Resource ID: {0} “, perm.ResourceId); Console.WriteLine(“Permission Mode: {0} “, perm.PermissionMode); Console.WriteLine(“Token: {0} “, perm.Token); Console.WriteLine(“Timestamp: {0} “, perm.Timestamp); } This time, it”s a permission query against the user”s permissions link and we simply list each permission returned for the user. Let”s delete the Alice’s and Tom’s permissions. await DeletePermission(client, alice, “Alice Collection Access”); await DeletePermission(client, tom, “Tom Collection Access”); Following is the implementation for DeletePermission. private async static Task DeletePermission(DocumentClient client, User user, string permId) { Console.WriteLine(); Console.WriteLine(“**** Delete Permission {0} from {1} ****”, permId, user.Id); var query = new SqlQuerySpec { QueryText = “SELECT * FROM c WHERE c.id = @id”, Parameters = new SqlParameterCollection { new SqlParameter { Name = “@id”, Value = permId } } }; Permission perm = client.CreatePermissionQuery(user.PermissionsLink, query) .AsEnumerable().First(); await client.DeletePermissionAsync(perm.SelfLink); Console.WriteLine(“Deleted permission {0} from user {1}”, permId, user.Id); } Step 6 − To delete permissions, query by permission Id to get the SelfLink, and then using the SelfLink to delete the permission. Next, let’s delete the users themselves. Let’s delete both the users. await DeleteUser(client, “Alice”); await DeleteUser(client, “Tom”); Following is the implementation for DeleteUser. private async static Task DeleteUser(DocumentClient client, string userId) { Console.WriteLine(); Console.WriteLine(“**** Delete User {0} in {1} ****”, userId, database.Id); var query = new SqlQuerySpec { QueryText = “SELECT * FROM c WHERE c.id = @id”, Parameters = new SqlParameterCollection { new SqlParameter { Name = “@id”, Value = userId } } }; User user = client.CreateUserQuery(database.SelfLink, query).AsEnumerable().First(); await client.DeleteUserAsync(user.SelfLink); Console.WriteLine(“Deleted user {0} from database {1}”, userId, database.Id); } Step 7 − First

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 ”;