Quickstart: Create a console app with Java and the MongoDB API in Azure Cosmos DB
APPLIES TO: Azure Cosmos DB API for MongoDB
In this quickstart, you create and manage an Azure Cosmos DB for MongoDB API account from the Azure portal, and add data by using a Java SDK app cloned from GitHub. Azure Cosmos DB is a multi-model database service that lets you quickly create and query document, table, key-value, and graph databases with global distribution and horizontal scale capabilities.
- An Azure account with an active subscription. Create one for free. Or try Azure Cosmos DB for free without an Azure subscription. You can also use the Azure Cosmos DB Emulator with the connection string
- Java Development Kit (JDK) version 8.
- Maven. Or run
apt-get install mavento install Maven.
Create a database account
In a new browser window, sign in to the Azure portal.
In the left menu, select Create a resource.
On the New page, select Databases > Azure Cosmos DB.
On 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 name as Account Name
Select Create new. Then enter a new resource group name for your account. For simplicity, use the same name as your Azure Cosmos DB account name. Account Name Enter a unique name Enter a unique name to identify your Azure Cosmos DB account. Your account URI will be mongo.cosmos.azure.com appended to your unique account name.
The account name can use only lowercase letters, numbers, and hyphens (-), and must be between 3 and 31 characters long.
API Azure Cosmos DB for Mongo DB API 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 for Mongo DB API for document databases, Azure Table, and Cassandra. Currently, you must create a separate account for each API.
Select Azure Cosmos DB for Mongo DB API because in this quickstart you are creating a collection that works with MongoDB.
Learn more about Azure Cosmos DB for MongoDB API.
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. Capacity mode Provisioned throughput or Serverless Select Provisioned throughput to create an account in provisioned throughput mode. Select Serverless to create an account in serverless mode.
Note: Only MongoDB API version 3.6 is supported by serverless accounts. Choosing 3.2 as the version will force the account in provisioned throughput mode.
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 Azure Cosmos DB for Mongo DB API account 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 an Azure Cosmos DB's API for MongoDB 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 db Enter db 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. You can also choose Autoscale mode, which will give you a range of RU/s that will dynamically increase and decrease as needed. Collection ID coll Enter
collas the name for your new container. Container IDs have the same character requirements as database names.
Storage capacity Fixed (10GB) Enter Fixed (10GB) for this application. If you select Unlimited, you will have to create a
Shard Key, which all items inserted will require.
Shard key /_id The sample described in this article does not use a Shard Key, so setting it to /_id will use the automatically generated ID field as the shard key. Learn more about sharding, also known as partitioning, in Partitioning in Azure Cosmos DB
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.
This console app uses the MongoDB Java driver.
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 your Azure Cosmos DB account, select Quick Start, select Java, then copy the connection string to your clipboard.
Open the Program.java file, 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 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 Search bar, search for and select Resource groups.
From the list, select the resource group you created for this quickstart.
On the resource group Overview page, select Delete resource group.
In the next window, enter the name of the resource group to delete, and then select Delete.
In this quickstart, you learned how to create an Azure Cosmos DB API for Mongo DB account, add a database and container using Data Explorer, and add data using a Java console app. You can now import additional data to your Cosmos database.