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.

Prerequisites

Create a database account

  1. In a new browser window, sign in to the Azure portal.

  2. In the left menu, select Create a resource.

    Screenshot of creating a resource in the Azure portal.

  3. On the New page, select Databases > Azure Cosmos DB.

    Screenshot of the Azure portal Databases pane.

  4. 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.

    Screenshot of the Select API option pane.

  5. 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.

    Note

    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.

    Screenshot of the new account page for Azure Cosmos DB.

  6. 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.

    Note

    The following options are not available if you select Serverless as the Capacity mode:

    • Apply Free Tier Discount
    • Geo-redundancy
    • Multi-region Writes
  7. 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.
  8. Select Review + create.

  9. 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.

    Screenshot of the Azure portal Notifications pane.

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.

  1. Select Data Explorer > New Container.

    The Add Container area is displayed on the far right, you may need to scroll right to see it.

    The Azure portal Data Explorer, Add Container pane

  2. 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 coll as 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.

  1. Open a command prompt, create a new folder named git-samples, then close the command prompt.

    md "C:\git-samples"
    
  2. Open a git terminal window, such as git bash, and use the cd command to change to the new folder to install the sample app.

    cd "C:\git-samples"
    
  3. 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
    
  4. 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 MongoCollection.insertOne

    Document document = new Document("fruit", "apple")
    collection.insertOne(document);
    
  • Some queries are performed using MongoCollection.find

    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.

  1. From your Azure Cosmos DB account, select Quick Start, select Java, then copy the connection string to your clipboard.

  2. 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

  1. Run mvn package in a terminal to install required packages

  2. Run mvn exec:java -D exec.mainClass=GetStarted.Program in a terminal to start your Java application.

You can now use Robomongo / Studio 3T to query, modify, and work with this new data.

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:

  1. Select Metrics in your Azure Cosmos DB account's navigation menu.

  2. Select a tab such as Latency, and select a timeframe on the right. Compare the Actual and SLA lines on the charts.

    Azure Cosmos DB metrics suite

  3. 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:

  1. In the Azure portal Search bar, search for and select Resource groups.

  2. From the list, select the resource group you created for this quickstart.

    Select the resource group to delete

  3. On the resource group Overview page, select Delete resource group.

    Delete the resource group

  4. In the next window, enter the name of the resource group to delete, and then select Delete.

Next steps

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.