Quickstart: Build a web app using Azure Cosmos DB's API for MongoDB and Java SDK
Azure Cosmos DB is Microsoft’s globally distributed multi-model database service. You can quickly create and query document, key/value and graph databases, all of which benefit from the global distribution and horizontal scale capabilities at the core of Cosmos DB.
Before you can run this sample, you must have the following prerequisites:
- [Install the JDK for Azure and Azure Stack JDK version 8] (https://aka.ms/azure-jdks)
- Maven (Run
apt-get install mavenif you don't have Maven)
Alternatively, you can Try Azure Cosmos DB for free without an Azure subscription, free of charge and commitments. Or you can use the Azure Cosmos DB Emulator for this tutorial with a connection string of
Create a database account
In a new window, sign in to the Azure portal.
In the left menu, click Create a resource, click Databases, and then under Azure Cosmos DB, click Create.
In the Create Azure Cosmos DB Account page, enter the settings for the new Azure Cosmos DB account.
Setting Value Description Subscription Your subscription Select the Azure subscription that you want to use for this Azure Cosmos DB account. Resource Group Create new
Then enter the same unique name as provided in ID
Select Create new. Then enter a new resource-group name for your account. For simplicity, use the same name as your ID. Account Name Enter a unique name Enter a unique name to identify your Azure Cosmos DB account. Because documents.azure.com is appended to the ID that you provide to create your URI, use a unique ID.
The ID can use only lowercase letters, numbers, and the hyphen (-) character. It must be between 3 and 31 characters in length.
API Azure Cosmos DB's API for MongoDB The API determines the type of account to create. Azure Cosmos DB provides five APIs: Core (SQL) for document databases, Gremlin for graph databases, Azure Cosmos DB's API MongoDB for document databases, Azure Table, and Cassandra. Currently, you must create a separate account for each API.
Select MongoDB because in this quickstart you are creating a table that works with the MongoDB.
Location Select the region closest to your users Select a geographic location to host your Azure Cosmos DB account. Use the location that's closest to your users to give them the fastest access to the data.
Select Review+Create. You can skip the Network and Tags section.
The account creation takes a few minutes. Wait for the portal to display the Congratulations! Your Cosmos account with wire protocol compatibility for MongoDB is ready page.
Add a collection
Name your new database, db, and your new collection, coll.
You can now use the Data Explorer tool in the Azure portal to create a database and container.
Select Data Explorer > New Container.
The Add Container area is displayed on the far right, you may need to scroll right to see it.
In the Add container page, enter the settings for the new container.
Setting Suggested value Description Database ID Tasks Enter ToDoList as the name for the new database. Database names must contain from 1 through 255 characters, and they cannot contain
/, \\, #, ?, or a trailing space. Check the Provision database throughput option, it allows you to share the throughput provisioned to the database across all the containers within the database. This option also helps with cost savings.
Throughput 400 Leave the throughput at 400 request units per second (RU/s). If you want to reduce latency, you can scale up the throughput later. Container ID Items Enter Items as the name for your new container. Container IDs have the same character requirements as database names. Partition key /category The sample described in this article uses /category as the partition key.
In addition to the preceding settings, you can optionally add Unique keys for the container. Let's leave the field empty in this example. Unique keys provide developers with the ability to add a layer of data integrity to the database. By creating a unique key policy while creating a container, you ensure the uniqueness of one or more values per partition key. To learn more, refer to the Unique keys in Azure Cosmos DB article.
Select OK. The Data Explorer displays the new database and container.
Clone the sample application
Now let's clone an app from GitHub, set the connection string, and run it. You'll see how easy it is to work with data programmatically.
Open a command prompt, create a new folder named git-samples, then close the command prompt.
Open a git terminal window, such as git bash, and use the
cdcommand to change to the new folder to install the sample app.
Run the following command to clone the sample repository. This command creates a copy of the sample app on your computer.
git clone https://github.com/Azure-Samples/azure-cosmos-db-mongodb-java-getting-started.git
Then open the code in your favorite editor.
Review the code
This step is optional. If you're interested in learning how the database resources are created in the code, you can review the following snippets. Otherwise, you can skip ahead to Update your connection string.
The following snippets are all taken from the Program.java file.
The DocumentClient is initialized.
MongoClientURI uri = new MongoClientURI("FILLME");` MongoClient mongoClient = new MongoClient(uri);
A new database and collection are created.
MongoDatabase database = mongoClient.getDatabase("db"); MongoCollection<Document> collection = database.getCollection("coll");
Some documents are inserted using
Document document = new Document("fruit", "apple") collection.insertOne(document);
Some queries are performed using
Document queryResult = collection.find(Filters.eq("fruit", "apple")).first(); System.out.println(queryResult.toJson());
Update your connection string
Now go back to the Azure portal to get your connection string information and copy it into the app.
From the Account, select Quick Start, select Java, then copy the connection string to your clipboard
Program.javafile, replace the argument to the MongoClientURI constructor with the connection string. You've now updated your app with all the info it needs to communicate with Azure Cosmos DB.
Run the console app
mvn packagein a terminal to install required npm modules
mvn exec:java -D exec.mainClass=GetStarted.Programin a terminal to start your Java application.
Review SLAs in the Azure portal
The Azure portal monitors your Cosmos DB account throughput, storage, availability, latency, and consistency. Charts for metrics associated with an Azure Cosmos DB Service Level Agreement (SLA) show the SLA value compared to actual performance. This suite of metrics makes monitoring your SLAs transparent.
To review metrics and SLAs:
Select Metrics in your Cosmos DB account's navigation menu.
Select a tab such as Latency, and select a timeframe on the right. Compare the Actual and SLA lines on the charts.
Review the metrics on the other tabs.
Clean up resources
When you're done with your web app and Azure Cosmos DB account, you can delete the Azure resources you created so you don't incur more charges. To delete the resources:
In the Azure portal, select Resource groups on the far left. If the left menu is collapsed, select to expand it.
Select the resource group you created for this quickstart.
In the new window, select Delete resource group.
In the next window, type the name of the resource group to delete, and then select Delete.
In this quickstart, you've learned how to create a Cosmos account, create a collection and run a console app. You can now import additional data to your Cosmos database.
Send feedback about: