Quickstart: Create a console app with Java and the API for MongoDB in Azure Cosmos DB
APPLIES TO: MongoDB
In this quickstart, you create and manage an Azure Cosmos DB for API for MongoDB 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 Select API option page, select Azure Cosmos DB for MongoDB > Create.
The API determines the type of account to create. Select Azure Cosmos DB for MongoDB because you will create a collection that works with MongoDB in this quickstart. To learn more, see Overview of Azure Cosmos DB for MongoDB.
On the Create Azure Cosmos DB Account page, enter the settings for the new Azure Cosmos DB account.
Setting Value Description Subscription Subscription name Select the Azure subscription that you want to use for this Azure Cosmos DB account. Resource Group Resource group name Select a resource group, or select Create new, then enter a unique name for the new resource group. 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 44 characters long.
Location The region closest to your users Select a geographic location to host your Azure Cosmos DB account. Use the location that is 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 API for MongoDB versions 4.2, 4.0, and 3.6 are supported by serverless accounts. Choosing 3.2 as the version will force the account in provisioned throughput mode.
Apply Azure Cosmos DB free tier discount Apply or Do not apply With Azure Cosmos DB free tier, you will get the first 1000 RU/s and 25 GB of storage for free in an account. Learn more about free tier. Version Choose the required server version Azure Cosmos DB for MongoDB is compatible with the server version 4.2, 4.0, 3.6, and 3.2. You can upgrade or downgrade an account after it is created.
You can have up to one free tier Azure Cosmos DB account per Azure subscription and must opt-in when creating the account. If you do not see the option to apply the free tier discount, this means another account in the subscription has already been enabled with free tier.
In the Global Distribution tab, configure the following details. You can leave the default values for the purpose of this quickstart:
Setting Value Description Geo-Redundancy Disable Enable or disable global distribution on your account by pairing your region with a pair region. You can add more regions to your account later. Multi-region Writes Disable Multi-region writes capability allows you to take advantage of the provisioned throughput for your databases and containers across the globe.
The following options are not available if you select Serverless as the Capacity mode:
- Apply Free Tier Discount
- Multi-region Writes
Optionally you can configure additional details in the following tabs:
- Networking - Configure access from a virtual network.
- Backup Policy - Configure either periodic or continuous backup policy.
- Encryption - Use either service-managed key or a customer-managed key.
- Tags - Tags are name/value pairs that enable you to categorize resources and view consolidated billing by applying the same tag to multiple resources and resource groups.
Select Review + create.
The account creation takes a few minutes. Wait for the portal to display the Congratulations! Your Azure Cosmos DB for MongoDB 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 Azure 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 Azure 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 for MongoDB 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 Azure Cosmos DB database.
Trying to do capacity planning for a migration to Azure Cosmos DB? You can use information about your existing database cluster for capacity planning.
- If all you know is the number of vcores and servers in your existing database cluster, read about estimating request units using vCores or vCPUs
- If you know typical request rates for your current database workload, read about estimating request units using Azure Cosmos DB capacity planner