Getting Started with CosmosDB Development and NoSQL Document Databases

In this chapter, we will provision a Cosmos DB account that uses the SQL API and we will start working with a document database, its collections, and documents. We will work with Cosmos DB on Azure and we will also learn how to work with the Azure Cosmos DB Emulator. We will work with different tools to interact with our Cosmos DB document database that will be extremely useful for our common development tasks. We will do the following:

  • Understand URIs, read-write and read-only keys, and connection strings
  • Create a new document database with the SQL API
  • Create a new collection
  • Populate a collection with documents
  • Understand automatically generated key-value pairs
  • Understand schema-agnostic features
  • Work with the web-based Azure Cosmos DB Explorer
  • Use Azure Storage Explorer to interact with Cosmos DB databases
  • Work with the Azure Cosmos DB Emulator

Provisioning a Cosmos DB account that uses the SQL API

In Chapter 1, Introduction to NoSQL in Cosmos DB, we learned about the different elements of the Cosmos DB resource model. Now we will use the web-based Azure portal to provision a Cosmos DB account with the SQL API. Then, we will create a document database, generate a collection for this database, and populate the collection with many JSON documents.

In order to follow the next steps, you have the following three options:

  • Work with an already active Azure account
  • Sign up for a new Azure account
  • Use the limited-time try Cosmos DB for free feature

If you want to work with an already active Azure account, you have to take into account that you will spend credits and, based on your free resources or credits, you can end up being billed for the storage, request units, and bandwidth consumed.

If you don't have an active Azure account, you can take advantage of the free $200 in Azure credits that you will receive to explore the services for 30 days when you sign up for a new Azure account. After 30 days, you will continue to have the account available to you, but you will start to be billed for the services. Note that the conditions usually change, so make sure you review them before signing up for these kinds of offers.

At the time I was writing this book, Microsoft made it possible to try Cosmos DB for free for a limited time, with no subscription or credit card number required. If you want to use this option to work with the samples in this book, you can sign up for a free account here: https://azure.microsoft.com/en-us/try/cosmosdb/.

If none of the previous options are suitable for you, you can work with the Azure Cosmos DB Emulator. However, it is highly recommended that you take a look at how things work on the Azure portal before moving to the emulator. In most cases, it will be convenient to combine work with Cosmos DB in Azure with the use of the emulator to reduce software development costs. We will analyze the use of the Azure Cosmos DB Emulator later in this chapter, in the Working with the Azure Cosmos DB Emulator section. So, make sure you don't skip that section.

Once you have selected the most convenient option for you, open a web browser and sign in to Microsoft Azure in the Azure portal, https://portal.azure.com/:

Click Create a resource | Databases | Azure Cosmos DB. The following screenshot shows these options in the Azure portal:

Enter a unique name to identify the new Azure Cosmos DB account in the ID textbox. Note that Azure will append .documents.azure.com to the value you enter for the ID textbox. The name can contain only lowercase letters, numbers, and the hyphen (-) character, and must be between 3 and 31 characters. In this case, I will use example001, Azure will generate an ID equal to example001.documents.azure.com, and the URI for the account will be https://example001.documents.azure.com:443/. Make sure you specify a value that the portal indicates as available after you enter it.

Select SQL in the API dropdown. This way, we will be able to create document databases that will use the SQL API in the account.

Select the Azure subscription that you want to use for the new Cosmos DB account in the Subscription dropdown. Don't forget that your Azure subscription might be charged, and therefore you should review the selected subscription name twice before creating the account.

Select the Create new option in Resource Group and enter the same name specified in the ID textbox. In this case, I will also use example001.

Select the most convenient region for you, based on your location, in the Location dropdown. This selection must take into account the available latency and the charges associated with the location. In this case, I will select East US. We won't take advantage of geo-redundancy or multi-master features. We want the basic features for a Cosmos DB account. The following screenshot shows the Azure Cosmos DB New account panel with sample values for the different options:

Click Create. Azure will validate the selected options. If all the options are valid, Azure will start the necessary processes to provision the new Cosmos DB account.

Click on the Notifications icon (a bell at the top-right corner) and you will see a Deployment in progress... notification indicating that the processes for creating the new Cosmos DB account are running. The following screenshot shows a sample of the notification:

In a few minutes, the portal will finish the deployment and it will display a Quick start panel indicating that the Cosmos DB account has been created. The following screenshot shows that panel, which provides quick start tabs for establishing a connection with the new account with diverse programming language and platform options available:

In this case, we follow the necessary steps to create a Cosmos DB account. As happens with most tasks in Azure, it is possible to automate these tasks that create resources with different scripting mechanisms, such as the cmdlets provided by Azure PowerShell and the Azure Resource Manager templates.

Understanding URIs, read-write and readonly keys, and connection strings

After you create a new Cosmos DB account, you will see the Quick start panel. However, the next time you sign in to the Azure portal, you won't see this panel. So, we will follow the necessary steps to access the recently created Cosmos DB account panel, considering we signed out and then signed in to the portal again:

Click Azure Cosmos DB in the left-hand panel. The portal will display a list with all the Cosmos DB accounts, their statuses, locations, and the subscription to which they belong. Note that if you have multiple Azure subscriptions, the list will include only the accounts for the selected subscription. Make sure you select the subscription with which you have created the account. The following screenshot shows a sample list that includes the example001 Cosmos DB account:

Click on the name for the recently created Cosmos DB account (example001) and the portal will open the page for this account with a menu at the left-hand side, and it will select the Overview option, which displays a panel at the righthand side. Overview shows a toolbar at the top, information about the account in the top panel, and the Collections, Regions, and Monitoring panels. This page will be our entry point for performing many operations for our new Cosmos DB account in the Azure portal. The following screenshot shows some of the elements of the page and the Overview panel. Note that, in this case, the Cosmos DB account has only one region configured:

Click on the Keys option on the left-hand side menu, located below the SETTINGS title. The portal will display the Keys panel with two tabs: Readwrite Keys and Read-only Keys. The following screenshot shows sample information provided by the Read-write Keys tab:

The Read-write Keys tab provides the following data, which we can copy to use different tools, SDKs, and programming languages to establish a read-write connection with the Cosmos DB account:

  • URI: This is also known as the endpoint URL or Cosmos DB account endpoint. The URI includes the ID value we used to create our Cosmos DB account. For example, if the ID value is example001, the URI is https://example001.documents.azure.com:443/.
  • Primary key: We can use this key as the authorization key in combination with the URI to establish a read-write connection with our Cosmos DB account.
  • Secondary key: If we don't want to share the primary key, we can provide the secondary key to be used as the authorization key in combination with the URI to establish a read-write connection with our Cosmos DB account. In addition, the availability of two keys makes it possible to perform key rotation without service disruption.
  • Primary connection string: This is a connection string that uses the URI and the primary key as the authorization key.
  • Secondary connection string: This is a connection string that uses the URI and the secondary key as the authorization key.

In some cases, we will use the URI and the primary key, and in other cases, we will use the primary connection string to establish a read-write connection with our Cosmos DB account. It is possible to regenerate both the primary and secondary keys by clicking on the regenerate icons located at the right-hand side of the copy icon of each key. If we regenerate a key, the related connection string will be updated to use the new key.

Whenever we require the URI, primary key, or primary connection string in the next sections, we will be using the values retrieved in the Readwrite keys tab.

If you need to work with read-only keys because you don't want to enable changes in the Cosmos DB account for any specific connection, you can use the keys and connection strings provided in the Read-only Keys tab.

Creating a new document database with the SQL API

We have a Cosmos DB account that works with the SQL API but we still don't have a database. Now we will continue working with the Azure web-based portal and we will create a new document database in the previously created account. We must take into account that we can use other tools, which we will analyze later, to perform this task. It is also possible to automate the task through scripting and to create a new database by using one of the available SDKs. However, it is a good idea to learn how things work in the portal first:

  • Make sure you are on the page for the Cosmos DB account in the portal. Click on the Data Explorer option on the left-hand side menu. The portal will display the Data Explorer panel, which will allow us to work with the databases for the current Cosmos DB account. In this case, the panel won't list any databases because we haven't created any yet.
  • Click on New Database in the toolbar located at the top of the panel. The New Database panel will appear.
  • Enter Competition in Database id. We don't want to provision throughput at the database level, so leave the Provision throughput checkbox unselected. This way, we will provision throughput per collection.
  • Click OK. Azure will create the new document database with the SQL API and, after a few seconds, the database name will be added to the list of databases at the left-hand side, below the SQL API title, as shown in the next screenshot:

After you finish working with the examples, make sure you delete all the resources you have been creating when you don't need them anymore. If you don't delete the resources and you work with an Azure subscription instead of using the emulator, you will spend any remaining Azure credits and you could end up being billed.

Creating a new collection

Now we will create a new collection for the database.

Hover on the database name (Competition) and click on the ellipses at the right-hand side (...) to display a context menu, as shown in the next screenshot:

Click on New Collection in the context menu. The Add Collection panel will appear.

Enter VideoGames1 in Collection Id.

Select Fixed (10 GB) in Storage capacity. This way, the maximum storage size for the collection will be 10 GB. In this case, we won't configure a partition key.

Enter 1000 in Throughput (400 - 10,000 RU/s). This way, Azure will provision 1,000 request units per second for this collection. Note that based on the value we enter, the portal displays the estimated spend below this field.

Click + Add unique key and a new textbox will be added below Unique keys. Enter /name in this textbox to specify that we want the name value to be unique per partition key. In this case, there is only one partition, and therefore, the data integrity layer will make sure the name value will be unique in this collection. The following screenshot shows the Add Collection panel with the values explained:

Click OK. Azure will create the new document collection named VideoGames1.

Click on the database name (Competition) at the left-hand side, below the SQL API title, and the new collection will be shown. Click on the VideoGames1 collection and you will see the following items:

  • Documents
  • Scale & Settings
  • Stored Procedures
  • User Defined Functions
  • Triggers

In addition, the Documents tab will display a query that retrieves all the existing documents for the new collection. As we just created the collection, it is empty and the result set shows no documents. The following screenshot shows the Documents tab for the new collection and the notifications panel at the bottom, with the results of all the tasks we have been performing in the portal:

Populating a collection with documents

Now we will populate the recently created collection with a few documents that represent games that were part of eSports competitions with specific tags, definitions for their levels, and the high score achievements. We will continue working with the Azure web-based portal, but we will learn to use other tools to perform the same task in the following sections.

Create a new JSON file with the following contents in your favorite text editor and save it in a temporary folder as videogame1_01.json. The following lines show the code that defines the game with its tags, levels, and high score achievements. The code file for the sample is included in the learning_cosmos_db_02_01 folder in the videogames/videogame1_01.json file:

{
    "id": "1",
    "name": "Battle Royale Kingdoms",
    "lastCompetitionDate": "2018-09-29T04:36:22.7251173Z",
    "tags": [
        "mobile", "2D", "card game"
    ],
    "levels": [
        {
            "title": "Training Camp for Dummies",
            "towers": 2,
            "towerPower": 30
        },
        {
            "title": "Jungle Arena",
            "towers": 2,
            "towerPower": 40
        },
        {
            "title": "Legendary World",
            "towers": 5,
            "towerPower": 100
        }
    ],
    "highestScores": [
        {             "player":
            {
                "nickName": "Brandon in Wonderland",
                "clan": "Wonderland Warriors"
            },
            "score": "750"
        }
    ]
}

The JSON document has arrays and nested documents. The JSON document defines the following keys:

  • id: The game ID. Note that we must use a string ID for the JSON documents that we want to store in a Cosmos DB SQL API collection. name: The game's name.
  • lastCompetitionDate: The last date and time at which the game was played in an eSports competition. tags: An array of strings with tags related to the game.
  • levels: An array of JSON objects that defines the different levels that the game has. In this case, each level has a title, a number of towers, and the tower's power value.
  • highestScores: An array of JSON documents that specifies the players nicknames, clans, and their high scores for the game in eSports competitions. Note that the player is a nested JSON document with the nickName and clan keys.

Copy the content of the JSON document to the clipboard.

Click New Document on the toolbar below the Documents tab. The portal will display a JSON editor with the following lines that indicate that you must provide a string value for the id key:

{
    "id": "replace_with_new_document_id"
}

The id key is always required and represents the unique identifier that identifies the document within the collection. So, we won't be able to add another document with the same ID to the same collection. The ID must be a string with a maximum of 255 characters.

Select all the content in the editor and paste the content of the clipboard. This way, you will replace the previous lines with the JSON document you created with your favorite text editor for JSON content. The text editor provided by the portal uses syntax highlighting and error indicators for the JSON content. So, if the JSON document has issues, you will notice them before trying to insert a new document into the collection and the Save button will be disabled.

Click Save on the toolbar below the Documents tab. The new document will be inserted into the VideoGames1 collection, and the portal will display the id for the new document in the list at the left-hand side and the inserted document in the editor at the right-hand side. The following screenshot shows the added document:

Understanding automatically generated keyvalue pairs

Scroll down to the latest lines of the document in the web-based editor and you will see new key-value pairs that were not part of the original document. The following screenshot shows the last lines in the embedded JSON editor:

The following lines show an example of the new key-value pairs. Note that many values will be different in your case:

"_rid": "prUNAKtPjRoFAAAAAAAAAA==",     "_self":
"dbs/prUNAA==/colls/prUNAKtPjRo=/docs/prUNAKtPjRoFAAAAAAAAAA==/",
    "_etag": "\"22007fea-0000-0000-0000-5b86dbd60000\"",
    "_attachments": "attachments/",
    "_ts": 1535564758
}

Cosmos DB added the following keys to our document, which start with an underscore (_) as a prefix and contain system-generated values for the document resource:

  • _rid: This string defines the resource ID; that is, a unique identifier for the resource. Cosmos DB uses this resource ID internally to identify and navigate through the document resource.
  • _self: This string provides a unique addressable URI for the resource, also known as a self link. When we work with the different SDKs, we can use the self link to easily identify a document or other resources that provide a self link. This URI is the combination of the self links for the database and the collection to which the document belongs. In fact, the self link includes the hierarchical paths to the resource stack. For example, the previous lines showed that the value for _self was "dbs/prUNAA==/colls/prUNAKtPjRo=/docs/prUNAKtPjRoFAAAAAAAAAA==/", which includes the paths to the self links for the database resource, "dbs/prUNAA==" and the collection resource, "dbs/prUNAA==/colls/prUNAKtPjRo=". The self link uses a slash (/) as the path separator.
  • _etag: This string stores the entity tag that Cosmos DB uses for optimistic concurrency control.
  • _attachments: This string stores the addressable path of the attachment resource related to the document that provides information about the attachments. A document can contain many attachments, which are special documents that contain references and associated metadata with an external blob or media file.
  • _ts: This integer stores a timestamp with the last date and time in which the document has been updated. Whenever a document is updated, the value for _ts will change.

In this case, we analyzed the system-generated key-value pairs for a document. These values are also added whenever we create other resources through an SDK, such as databases and collections. So, whenever we have to address a resource, we can take advantage of the self link; that is, the value of the _self property for the resource.

Understanding schema-agnostic features

Now we will add another document to the same collection. In this case, the new document will have new keys that didn't exist in the previously inserted document.

Create a new JSON file with the following contents in your favorite text editor and save it in a temporary folder as videogame1_02.json. The following lines show the code that defines a new game with its tags, levels, high score achievements, and prizes. The code file

for the sample is included in the learning_cosmos_db_02_01 folder in the videogames/videogame1_02.json file:

{
    "id": "2",
    "name": "Fortnite vs Zombies",
    "lastCompetitionDate": "2018-09-30T03:31:20.7251173Z",
    "tags": [
        "3D", "battle royale", "monsters", "shooter"
    ],
    "platforms": [
        "PS4", "XBox", "PC", "Switch", "iPad", "iPhone", "Android"
    ],
    "levels": [
        {
            "title": "Dancing in the storm",
            "maximumPlayers": 50,
            "minimumExperienceLevel": 30
        },
        {
            "title": "Rainbows after the storm",
            "maximumPlayers": 30,
            "minimumExperienceLevel": 60
        },
        {
            "title": "The last of us",
            "maximumPlayers": 10,
            "minimumExperienceLevel": 100
        }
    ],
    "highestScores": [
        {             "player":
            {
                "nickName": "PlaystationBoy",
                "clan": "USA Players",
                "experienceLevel": 140
            },
            "score": "5600"
        },
        {             "player":
            {
                "nickName": "KevinSwitchMan",
                "clan": "Italian Warriors",
                "experienceLevel": 125
            },
            "score": "3300"
        }
    ]
}

The JSON document includes many keys and nested documents that were not included in the previously inserted document. The new JSON document defines a platforms key with an array of strings, with the platform names, in which the game can be executed.

In addition, the new JSON document has different formats for the levels and highestScores arrays. In this case, each level has a title, a maximum number of players, and a minimum experience level. In this document, each high score adds an experience level that wasn't included in the previous document. We are going to add a new document that has a different schema to that of the previous document.

Copy the content of the new JSON document to the clipboard.

Click New Document on the toolbar below the Documents tab. The portal will display a JSON editor.

Select all the content in the editor and paste the content of the clipboard. This way, you will replace the previous lines with the new JSON document you created with your favorite text editor for JSON content.

Click Save on the toolbar below the Documents tab. The new document will be inserted into the VideoGames1 collection and the portal will display the id for the new document in the list at the left-hand side and the inserted document in the editor at the right-hand side. The following screenshot shows the added document:

The document was successfully inserted, no matter the differences in the schema from the previous document that was added to the same collection. The document database with the SQL API is schema agnostic, and therefore we can have different schemas in each document we insert into the same collection without issues.

Scroll down to the latest lines of the document in the web-based editor and you will see the system-generated keys and their values, which we analyzed for the previously inserted document.

If you take a look at the value for the _self key for this document and compare it with the value of this key for the previous document, you will notice that they share the same prefix, because both documents belong to the same database and collection. The following are the two values I have after inserting the two documents. Note that the values will be different in your environment:

Document with id equal to 1:

"dbs/prUNAA==/colls/prUNAKtPjRo=/docs/prUNAKtPjRoFAAAAAAAAAA==/"

Document with id equal to 2:

"dbs/prUNAA==/colls/prUNAKtPjRo=/docs/prUNAKtPjRoGAAAAAAAAAA==/"

Working with the web-based Azure Cosmos DB Explorer

So far, we have been working with the portal and our screen real estate has been reduced as we selected new options that required additional panels. We can take advantage of Cosmos DB Explorer to open the Cosmos DB database account in a new browser tab and take advantage of a full-screen view.

Click Open Full Screen on the toolbar for the Cosmos DB database account. Cosmos DB will generate read-write and read-only access URLs that we can use to access the database and the collection in which we are working with Cosmos DB Explorer. The following screenshot shows a sample modal:

The URL will start with https://cosmos.azure.com/?key= followed by a key that will provide time-bound access to the Cosmos DB account with read-write or read-only access.

We just need to copy the URL and open it in a new browser tab. This way, we can work with Cosmos DB databases, collections, and documents with more screen real estate in any web browser. The following screenshot shows a web browser visualizing the previously created document, whose id is equal to 2, with Cosmos DB Explorer:

We can take advantage of Cosmos DB Explorer to provide a temporary URL to other users who need to work with a Cosmos DB account, without having to create Azure users for them. In fact, these users don't need to have access to the Azure portal or a subscription. However, if you specify security policies for your collections and documents, these users won't be able to work with them.

Using Azure Storage Explorer to interact with Cosmos DB databases

So far, we have been working with web-based interfaces to interact with a Cosmos DB Azure portal and Cosmos DB Explorer. The nice thing about web-based interfaces is that you can work with them in any compatible modern web browser on different devices. Now, we will explore a GUI tool that allows us to interact with Cosmos DB databases:

Microsoft Azure Storage Explorer. Initially, this tool was intended to work with other Azure storage services. However, at the end of 2017, the tool added support for working with Cosmos DB databases.

This tool is available on Windows, macOS, and Linux. You can download and install Azure Storage Explorer here: https://azure.microsoft.com/en-us/features/storage-explorer/. Note that the instructions that I will provide were tested with version 1.4.1 and that you need to work with specific versions of the operating systems in order to be able to run the tool; this might vary in versions higher than 1.4.1.

At the time I was writing this book, this tool could only work with SQL API and Table API Cosmos DB accounts.

Once you have installed Azure Storage Explorer, launch the tool and you will see a panel titled Explorer located at the left-hand side with the Cosmos DB Accounts option within Local & Attached.

Right-click on Cosmos DB Accounts and the application will display a context menu, shown in the next screenshot:

Select Connect to Cosmos DB... and the application will open a dialog box to specify the necessary parameters for establishing a connection with a Cosmos DB account.

Select SQL in the Select API dropdown because we want to work with the Cosmos DB we created with the SQL API.

Copy the primary connection string we learned how to grab in the Azure portal in the Understanding URIs, read-write and read-only keys, and connection strings section of this chapter. Make sure you use the primary connection string, which enables read-write access to the account. The connection string starts with AccountEndpoint=.

Paste the primary connection string in the Connection string textbox.

If you want to identify the Cosmos DB account with a different label than the proposed one, you can specify it in the Account label textbox.

The following screenshot shows an example of the configuration for the Connect to Cosmos DB dialog:

Click Next and the wizard will display the entered values so that you can confirm them. If they are correct, click Connect. Azure Storage Explorer will use the provided data to establish a connection with the Cosmos DB account and it will display the specified account label in the Cosmos DB Accounts list (example001) in the Explorer panel.

The application will allow you to navigate through the existing document database (Competition), its collection (VideoGames1), and its documents by expanding and clicking on the different elements. Once we reach the Documents element for the VideoGames1 collection, we will see a panel that provides a toolbar and an interface that is very similar to the web-based interface we used in the Azure portal and in Cosmos DB Explorer. The following screenshot shows the application displaying the details of the document whose id is equal to 2:

We can use Microsoft Azure Storage Explorer to perform the tasks we have been performing in the previous sections. The main difference is that we will see dialog boxes instead of the panels that we saw in the web-based interface.

Working with the Azure Cosmos DB Emulator

Sometimes, the Azure credit included in different subscriptions is enough for our development tasks. However, in other cases, we don't want to spend Azure credits or be billed for our development tasks that use Cosmos DB storage and services.

Microsoft provides the Azure Cosmos DB Emulator, which we can install on specific Windows versions, that emulates the Cosmos DB service without working with an Azure subscription or any other Azure service. The Azure Cosmos DB Emulator runs as an application that uses resources in the computer on which it is installed, and therefore makes it possible to perform many Cosmos DB operations and tests without incurring any Azure costs.

At the time I was writing this book, the emulator provided support for the SQL API and the MongoDB API. Other APIs were not available for use in the emulator data explorer. You can read more information about the emulator and download the latest binaries or Windows Docker images here:. https://docs.microsoft.com/en-us/azure/cosmos-db/localemulator

Unluckily, the emulator was only available for some specific Windows versions: Windows 10, Windows Server 2012 R2, Windows Server 2016, and Windows Server 2019.

After you install the emulator, you can work with its web-based data explorer or you can use the previously explained Microsoft Azure Storage Explorer to connect with it. You have to consider that even when the emulator is an active project and is continuously being improved, it has limitations on the number of collections and documents that you can create and doesn't have the same features that we have learned about so far for Cosmos DB. However, it will make it possible for us to run our sample applications. For example, you can perform all the tasks we have learned in the previous sections by working with the emulator.

After you execute the Azure Cosmos DB Emulator on Windows, right-click on its notification icon and select Open Data Explorer..., as shown in the next screenshot:

Your default web browser will go to https://localhost:8081/_explorer/index.html and you will see the Quickstart panel for the emulator, which will display the URI, primary key, and primary connection string for the SQL API. You can use these settings whenever you have to establish a connection to Cosmos DB and you will work with the emulator and your local resources instead of working with Azure Cosmos DB. We analyzed the meanings of these items in the Understanding URIs, read-write and read-only keys, and connection strings section of this chapter. In addition, the panel will display the connection string for the MongoDB API. The following screenshot shows the Quickstart panel:

You can access the data explorer for the emulator by clicking on Explorer in the left-hand panel. You will be able to create new databases, collections, and documents, as we did when working with the Azure portal.

If you work with the emulator, it is highly recommended to take advantage of the previously introduced Azure Storage Explorer. In order to connect with the emulator, launch the tool and you will see a panel titled Explorer located at the left-hand side with the Cosmos DB Accounts option in Local & Attached.

Select Connect to Cosmos DB Emulator... and the application will use the default parameters to establish a connection with the Azure Cosmos DB Emulator.

If you want to identify the Cosmos DB account with a different label than the proposed one, you can specify it in the Account label textbox. For example, you can specify Emulator.

Click Next and the wizard will display the entered values so that you can confirm them. If they are correct, click Connect. Azure Storage Explorer will use the provided data to establish a connection with the Azure Cosmos DB Emulator and it will display the specified account label in the Cosmos DB Accounts list (Emulator) in the Explorer panel.

The account that represents the emulator doesn't have a database yet, and therefore the first thing you will need to do is to create a database. Note that the account uses the default SQL API.

Test your knowledge

Let's see whether you can answer the following questions correctly:

  1. If we want to store a JSON document in a Cosmos DB SQL API collection, which of the following keys must have a value to provide the required unique identifier:
    1. id
    2. identifier
    3. uniqueId
  2. After a new document is added to a Cosmos DB SQL API collection, which of the following system-generated keys provides a unique addressable URI for the resource:
    1. _selfLink
    2. _selfURI
    3. _self
  3. After a new document is added to a Cosmos DB SQL API collection, which of the following system-generated keys provides a timestamp with the last date and time at which the resource was updated:
    1. _timeStamp
    2. _lastUpdateTS
    3. _ts
  4. We can establish a connection to a Cosmos DB account with:
    1. Only the Cosmos DB account URI or endpoint URL
    2. The Cosmos DB account URI or endpoint URL and the primary key as the authorization key
    3. The primary key and the secondary key concatenated to generate a single authorization key
  5. Which of the following values specify that we want the value for the name key at the root level of a document to be unique per partition key:
    1. +name
    2. . name
    3. /name

Summary

In this chapter, we provisioned a Cosmos DB account with the SQL API, and we created a document database and a collection. Then, we populated the collection with JSON documents and we understood the system-generated keys that Cosmos DB adds to a document resource. We ended up with a collection, containing documents with different structures, because we took advantage of the schema-agnostic feature of Cosmos DB.

We used the web-based Azure portal to perform the different tasks, and then we learned how to take advantage of screen real estate with Azure Cosmos DB Explorer. We worked with the Azure Storage Explorer GUI tool and we learned how to work with the Azure Cosmos DB Emulator to develop and test applications without being billed for the storage, request units, and bandwidth consumed.

Now that we have created our first Cosmos DB SQL API database, collection, and document, and we have explored the available tools, we will learn about building and running queries and taking advantage of indexing options, which are the topics we are going to discuss in the next chapter.