Setting Up Microsoft Azure DocumentDB

DocumentDB is the latest storage option added to Microsoft Azure. It is a NoSQL storage service that stores JSON documents natively and provides indexing capabilities along with other interesting features. This article shall introduce you to this new service.

Setting up a Microsoft Azure DocumentDB

Go to the new Microsoft Azure Portal.

Click on New, then Data + Storage, click DocumentDB

Enter a Database ID and hit Create.

Please wait while the database is being created.

After the database is created, KEYS button to get the Database URI and its required keys.

We may now start building our App.

Using Microsoft Azure DocumentDB in your Application

Create a new project and add the nuget package Microsoft Azure DocumentDB Client Library.

Go to Tools, then Library Package Manager and click Package Manager Console.

Key in Install-Package Microsoft.Azure.Documents.Client -Pre and hit enter.

Define the Model

In this example, we shall define a class Team, each having an array of players.

  1. public class Team  
  2. {  
  3.     [JsonProperty(PropertyName = "id")]  
  4.     public string Id { getset; }  
  5.     public string TeamName { getset; }  
  6.     public Player[] Players { getset; }  

  7. public class Player  
  8. {  
  9.     public string PlayerName { getset; }  
  10.     public int PlayerAge { getset; }  
  11. }  
Add the endpoint url and the authorization key.

These values are the same values identified above.
  1. private static string endpointUrl = "";  
  2. private static string authorizationKey = "";  
Create a new instance of the DocumentClient

The DocumentClient class provides a client-side logical representation of the Azure DocumentDB service. It is used to configure and execute requests against the service.
  1. client = new DocumentClient(new Uri(endpointUrl), authorizationKey);  
Create Database

This will return an instance of a database, first creating it if it doesn't already exist.
  1. public async Task<Database> CreateOrGet(string DatabaseID)  
  2. {  
  4.     var Databases = client.CreateDatabaseQuery().Where(db => db.Id == DatabaseID).ToArray();  
  6.     if (Databases.Any())  
  7.         return Databases.First();  
  9.     return await client.CreateDatabaseAsync(new Database { Id = DatabaseID });  
  10. }  
Create a document collection

This method returns a document collection, creating it if it doesn't already exist. A document collection is a named logical container for documents.

The method CreateDocumentCollectionQuery creates and returns a query for document collections.
  1. public async Task<DocumentCollection> CreateOrGetCollection(string CollectionID)  
  2. {  
  3.     var collections = client.CreateDocumentCollectionQuery(database.CollectionsLink)  
  4.                         .Where(col => col.Id == CollectionID).ToArray();  
  5.     if (collections.Any())  
  6.         return collections.First();  
  8.     return await client.CreateDocumentCollectionAsync(database.CollectionsLink,  
  9.         new DocumentCollection  
  10.         {  
  11.             Id = CollectionID  
  12.         });  
  13. }  
Create Documents

Create normal C# objects that represent documents.

Create Team Documents
  1. Team team1 = new Team  
  2. {  
  3.      Id="t001",  
  4.       TeamName="Football team 1",  
  5.       Players= new Player[]{  
  6.         new Player{ PlayerName="Chervine", PlayerAge=21},  
  7.         new Player { PlayerName="Kevin", PlayerAge=21}  
  8.       }  
  9. };  
  11. Team team2 = new Team  
  12. {  
  13.     Id = "t002",  
  14.     TeamName = "Football team 2",  
  15.     Players = new Player[]{  
  16.         new Player{ PlayerName="Cherv", PlayerAge=21},  
  17.         new Player { PlayerName="Kev", PlayerAge=21}  
  18.       }  
  19. };  
Save the documents

To save documents, the method CreateDocumentAsync is used that creates a document as an asynchronous operation.
  1. await client.CreateDocumentAsync(documentCollection.DocumentsLink, team1);  
  2. await client.CreateDocumentAsync(documentCollection.DocumentsLink, team2);  
The document is now saved.

You may now browse it from the Azure portal. From the dashboard, select your DocumentDB, scroll down to Document Explorer, and select the collections you wish to view.

Read data from the Application

You can use both SQL and LINQ to retrieve data in DocummentDB.

Using SQL

Retrieving one team
  1. team2 = client.CreateDocumentQuery<Team>(documentCollection.DocumentsLink, "SELECT * FROM Teams t WHERE t.TeamName = \"Football team 2\"").AsEnumerable().FirstOrDefault();  
Retrieving all teams
  1. foreach (var team in client.CreateDocumentQuery(documentCollection.DocumentsLink,  
  2. "SELECT * FROM Teams"))  
  3. {  
  4. Console.WriteLine("\tRead {0} from SQL", team);  
  5. }  
Using LINQ

Retrieving one team
  1. team1 = client.CreateDocumentQuery<Team>(documentCollection.DocumentsLink).Where(d => d.TeamName == "Football team 1").AsEnumerable().FirstOrDefault();  
Updating a document

You first need to get the document to update, make the changes and replace the document.
  1. dynamic Team2Doc = client.CreateDocumentQuery<Document>(documentCollection.DocumentsLink).Where(d => d.Id =="t002").AsEnumerable().FirstOrDefault();  
  2. Team2Doc.TeamName = "UPDATED_TEAM_2";  
  3. await client.ReplaceDocumentAsync(Team2Doc);  
Delete a document
  1. Document Team3Doc = client.CreateDocumentQuery<Document>(documentCollection.DocumentsLink).Where(d => d.Id =="t003").AsEnumerable().FirstOrDefault();  
  2. await client.DeleteDocumentAsync(Team3Doc.SelfLink)  

Microsoft Azure DocumentDB is really easy to use and allows for rapid application development.Being able to store heterogeneous JSON documents within DocumentDB and query it using SQL like syntax and LINQ is really great which means that the developer do not have to learn anything new.