Share via


How to Use Azure DocumentDB


Introduction

Azure Document DB is a No SQL Solution that stores its data in JSON format. It also allows complex queries to be executed rapidly in order to facilitate user needs. To use the resources, we must have an Azure DocumentDB database account which in turn can have multiple databases. Before Continuing we have to understand the following key areas of Document DB :

Collection

Container is a named logical container for documents. A Database can have zero or more collections.

Document

The document are JSON data that represents the record e.g. stored procedure, Triggers, UDFs etc. They can have different structures and fields. Remember, DocumentDB is schema free.

Users and Permissions

Users are Database users with defined access level call Permission. Permissions are athorized tokens that define to which collection resources the user have access to.

Figure 1 : Document DB Account Structure

To evaluate DocumentDB, log in to http://portal.azure.com with your account.

Configuration

After navigating to the portal, click the 'New' button and select DocumentDB.

Figure 2: Starting a new DocumentDB project

Fill in 'ID' and the 'Location' and click Create; this will create a DocumentDB account. Once the account is created, it starts appearing as a tile on the home page. Click the tile to see the details.

Figure 3: Viewing details

Figure 4: Viewing the Keys

Using Keys (Point 1 in Figure 4) helps you connect to the DocumentDB account. Point 2 in Figure 4 lists the different databases available in this account. When we click the database, it displays the different collections available within the database and clicking Collection displays the different records it contains.

Figure 5: Viewing the Keys, Part 2

Point 1 in Figure 5 displays the different collections in the database. Click Document Explorer (Point 2) to bring up the document explorer on the right, as shown in Point 3 of Figure 5. It displays the documents in the collection. Click the individual record to see the details, as shown in Figure 6:

Figure 6: Viewing the details

Let's write the code to add and update documents with the help of an example.

Connect to the DocumentDB Server from C# Code

Open Visual Studio 2013, click "Manage Nuget Package Manager", and install "Microsoft Azure DocumentDB Client Library". Ensure that "Include Prerelease" is selected.

Figure 7: Selecting "Include Prerelease"

To connect to the database and create documents, we first need to retrieve the URL and the key to connect. This information can be retrieved by clicking on "Keys" in Figure 4, Point 1.

Add the following namespaces:

using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;

Sample code to create a connection is:

private static string URI = "<URL>";
private static string Key = "<Key>";
private static DocumentClient client =
   new DocumentClient(new Uri(URI), Key);

Create a Schema Definition

In this example, I am using a console application to add and update records. We create two classes: Student and Marks. We will create the student first and then update the student with his or her marks.

 1. public class Student
 2. {
 3.    public string id { get; set; }
 4.    public string StudentNo { get; set; }
 5.    public string Name { get; set; }
 6.    public string Email { get; set; }
 7.    public string Address { get; set; }
 8.    public Marks StudentMarks { get; set; }
 9. }
 
10. public class Marks
11. {
12.    public int Marks1 { get; set; }
13.    public int Marks2 { get; set; }
14.    public int Marks3 { get; set; }
15. }

We have used two generic methods that check if the database or collection doesn't exist. If it doesn't yet exist, it creates it; otherwise, it returns the existing database or collection.

 1. public static async Task<Database> GetDatabase(string databaseName)
 2. {
 3.    if (client.CreateDatabaseQuery().Where(db => db.Id ==
          databaseName).AsEnumerable().Any())
 4.    {
 5.       return client.CreateDatabaseQuery().Where(db => db.Id ==
 6.          databaseName).AsEnumerable().FirstOrDefault();
 7.    }
 8.    return await client.CreateDatabaseAsync(new Database
          { Id = databaseName });
 9. }
 
10. public static async Task<DocumentCollection>
       GetCollection(Database database, string collName)
11. {
12.    if (client.CreateDocumentCollectionQuery
          (database.SelfLink).Where(coll => coll.Id ==
13.          collName).ToArray().Any())
14.    {
15.       return client.CreateDocumentCollectionQuery(database.SelfLink).
             Where(coll => coll.Id ==
16.       collName).ToArray().FirstOrDefault();
17.    }
18.    return await client.CreateDocumentCollectionAsync(database.SelfLink,
          new DocumentCollection
19.    { Id = collName });
20. }
Note: To resolve Query methods, ensure that the "using Microsoft.Azure.Documents.Linq;" namespace is added.

Now, we will use the generic methods to create the database and collection:

Database database = GetDatabase("StudentDatabase").Result;
DocumentCollection collection =
   GetCollection(database, "StudentList").Result;

Insert and Retrieve Information

To insert documents to the collection, we first create two objects for type Student.

 1. Student Joseph = new Student() { EmployeeNo = "3",
       Name = "Joseph S", Email = "Joseph.S@abc.com",
       Address = "Delhi, India" };
 2. Student Priya = new Student() { EmployeeNo = "4",
       Name = "Priya R", Email = "Priya.R@abc.com",
       Address = "Seattle, US" };

The following commands insert the documents into the collection.

 1. client.CreateDocumentAsync(collection.SelfLink, Joseph);
 2. client.CreateDocumentAsync(collection.SelfLink, Priya);

After the student documents are created, we update the students with their marks. Now, we create two marks objects.

 1. Marks JosephM = new Marks() { Marks1 = 10, Marks2 = 20,
       Marks3 = 30 };
 2. Marks PriyaM = new Marks() { Marks1 = 11, Marks2 = 21,
       Marks3 = 31 };

To update the existing documents, we first read the documents and then do an update. To do an update, we will need the internal guide for the document generated by Azure. For that reason, 'id' is added to the 'Student' class and it's not explicitly set in the code.

We also create an 'UpdateDocument' method to update the modified document back to the collection. To do that, we use the client.UpsertDocumentAsync method.

 1. public static async Task<Document>
    UpdateDocument(DocumentCollection coll, Student emp)
 2. {
 3.    return await
          client.UpsertDocumentAsync(coll.SelfLink, emp);
 4. }

Use the following command to retrieve documents from the collection. It uses a select clause that is similar to the corresponding SQL statement. In the following code, assign the marks to the two student records and call the 'UpdateDocument' function to update the collection.

 1. foreach (Student employee in client.CreateDocumentQuery(collection.SelfLink,
       "select * from EmployeeList"))
 2. {
 3.    if (employee.Name == "Joseph S")
 4.       employee.StudentMarks = JosephM;
 5.    else
 6.       employee.StudentMarks = PriyaM;
 
 7.    Document doc =
          UpdateDocument(collection, employee).Result;
 8.    Console.WriteLine("Employee Name: " + employee.Name +
          ", Address: " + employee.Address + " ,
 9.    Email: " + employee.Email);
10. }

After running this statement, we can go the 'Document Explorer' view. Refer to Fig 5, Point 2 to see the changes.

Summary

Document DB is a No SQL Azure Solution that provides all preconfigured and globally available URLs and stores its data in JSON that enables the data layer to evolve easily.

References

·         http://azure.microsoft.com/en-in/services/documentdb/

·         http://azure.microsoft.com/en-in/documentation/services/documentdb/