Share via


Creating and Querying Microsoft Azure DocumentDB

DocumentDB is the latest storage option added to Microsoft Azure.

It is a no-sql storage service that stores JSON documents natively and provides indexing capabilities along with other interesting features.

This wiki shall introduce you to this new service.

Setting up a Microsoft Azure DocumentDB

Go to the new Microsoft Azure Portal. https://portal.azure.com/

 

 Click on New >  Data + Storage > 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 project

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

Go to Tools > Package Manager > 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. 

public class  Team
{
    [JsonProperty(PropertyName = "id")]
    public string  Id { get; set; }
    public string  TeamName { get; set; }
    public Player[] Players { get; set; }
}
 
public class  Player
{
    public string  PlayerName { get; set; }
    public int  PlayerAge { get; set; }
}

Add the endpoint url and the authorization key.

These values are same values identified above.

private static  string endpointUrl = "";
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.

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.

public async Task<Database> CreateOrGet(string DatabaseID)
{
    
    var Databases = client.CreateDatabaseQuery().Where(db => db.Id == DatabaseID).ToArray();
 
    if (Databases.Any())
        return Databases.First();
 
    return await client.CreateDatabaseAsync(new Database { Id = DatabaseID });
}

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.

public async Task<DocumentCollection> CreateOrGetCollection(string CollectionID)
{
    var collections = client.CreateDocumentCollectionQuery(database.CollectionsLink)
                        .Where(col => col.Id == CollectionID).ToArray();
    if (collections.Any())
        return collections.First();
 
    return await client.CreateDocumentCollectionAsync(database.CollectionsLink,
        new DocumentCollection
        {
            Id = CollectionID
        });
}

Create Documents

Create normal c# objects that represent documents.

//Create Team Documents
Team team1 = new  Team
{
     Id="t001",
      TeamName="Football team 1",
      Players= new  Player[]{
        new Player{ PlayerName="Chervine", PlayerAge=21},
        new Player { PlayerName="Kevin", PlayerAge=21}
      }
};
 
Team team2 = new  Team
{
    Id = "t002",
    TeamName = "Football team 2",
    Players = new  Player[]{
        new Player{ PlayerName="Cherv", PlayerAge=21},
        new Player { PlayerName="Kev", PlayerAge=21}
      }
};

Save the documents

To save documents, the method CreateDocumentAsync is used which creates a document as an asynchronous operation.

await client.CreateDocumentAsync(documentCollection.DocumentsLink, team1);
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

team2 = client.CreateDocumentQuery<Team>(documentCollection.DocumentsLink, "SELECT * FROM Teams t WHERE t.TeamName = \"Football team 2\"").AsEnumerable().FirstOrDefault();

Retrieving all teams:

foreach (var team in client.CreateDocumentQuery(documentCollection.DocumentsLink,
"SELECT * FROM Teams"))
{
    Console.WriteLine("\tRead {0} from SQL", team);
}

Using LINQ

Retrieving one team:

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

Retrieving all teams:

foreach (var team in (
from t in  client.CreateDocumentQuery(documentCollection.DocumentsLink)
select t))
{
    Console.WriteLine("\tRead {0} from LINQ", team);

}

Updating a document

You first need to get the document to update, make the changes and replace the document.

dynamic Team2Doc = client.CreateDocumentQuery<Document>(documentCollection.DocumentsLink).Where(d => d.Id == "t002").AsEnumerable().FirstOrDefault();
Team2Doc.TeamName = "UPDATED_TEAM_2";
await client.ReplaceDocumentAsync(Team2Doc);

Delete a document

Document Team3Doc = client.CreateDocumentQuery<Document>(documentCollection.DocumentsLink).Where(d => d.Id == "t003").AsEnumerable().FirstOrDefault();
await client.DeleteDocumentAsync(Team3Doc.SelfLink)

Code Sample

​The code sample can be downloaded here.

Conclusion

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.

This service is still in preview mode and will get even more interesting with time.

Also, since it is still in preview mode, the materials presented in this wiki may change in the future.