Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
In this guide, you develop a Java console application to connect to an Azure DocumentDB cluster. The guide includes steps to set up your development environment, authenticate using the azure-identity package from the Azure SDK for Java, and interact with the database and collection to manage documents.
Prerequisites
An Azure subscription
- If you don't have an Azure subscription, create a free account
An existing Azure DocumentDB cluster
- If you don't have a cluster, create a new cluster
Use the Bash environment in Azure Cloud Shell. For more information, see Get started with Azure Cloud Shell.
If you prefer to run CLI reference commands locally, install the Azure CLI. If you're running on Windows or macOS, consider running Azure CLI in a Docker container. For more information, see How to run the Azure CLI in a Docker container.
If you're using a local installation, sign in to the Azure CLI by using the az login command. To finish the authentication process, follow the steps displayed in your terminal. For other sign-in options, see Authenticate to Azure using Azure CLI.
When you're prompted, install the Azure CLI extension on first use. For more information about extensions, see Use and manage extensions with the Azure CLI.
Run az version to find the version and dependent libraries that are installed. To upgrade to the latest version, run az upgrade.
Microsoft Entra authentication configured for the cluster with your identity granted
rootrole.- To enable Microsoft Entra authentication, review the configuration guide.
Latest version of Java.
Configure your console application
Next, create a new console application project and import the necessary libraries to authenticate to your cluster.
Create a new Maven project using the Maven command-line tools.
mvn archetype:generate -DgroupId=com.cosmicworks -DartifactId=mongodb-console-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=falseNavigate to the project directory.
cd mongodb-console-appCreate a new App.java file with a
Mainclass in the appropriate package directory.mkdir -p src/main/java/com/cosmicworks touch src/main/java/com/cosmicworks/App.javaAdd the
azure-identitydependency to your pom.xml file.<dependency> <groupId>com.azure</groupId> <artifactId>azure-identity</artifactId> <version>1.15.4</version> </dependency>Add the
mongodb-driver-syncdependency to your pom.xml file.<dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>5.4.0</version> </dependency>
Connect to the cluster
Now, use the Azure.Identity library to get a TokenCredential to use to connect to your cluster. The official MongoDB driver has a special interface that must be implemented to obtain tokens from Microsoft Entra for use when connecting to the cluster.
Start by importing the required classes at the top of your Java class file.
import java.util.concurrent.TimeUnit; import org.bson.Document; import org.bson.conversions.Bson; import com.azure.core.credential.TokenCredential; import com.azure.core.credential.TokenRequestContext; import com.azure.identity.DefaultAzureCredentialBuilder; import com.mongodb.MongoClientSettings; import com.mongodb.MongoCredential; import com.mongodb.MongoCredential.OidcCallbackContext; import com.mongodb.MongoCredential.OidcCallbackResult; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import com.mongodb.client.model.ReplaceOptions; import com.mongodb.client.result.UpdateResult;In your main method, create a
DefaultAzureCredentialinstance and set up the OpenID Connect (OIDC) callback to fetch tokens.TokenCredential credential = new DefaultAzureCredentialBuilder().build(); MongoCredential.OidcCallback oidcCallback = new MongoCredential.OidcCallback() { @Override public OidcCallbackResult onRequest(OidcCallbackContext context) { TokenRequestContext tokenRequestContext = new TokenRequestContext() .addScopes("https://ossrdbms-aad.database.windows.net/.default"); String token = credential.getTokenSync(tokenRequestContext).getToken(); return new OidcCallbackResult(token); } };Create a new instance of
MongoCredentialusing your previously defined callback.MongoCredential mongoCredential = MongoCredential.createOidcCredential(null) .withMechanismProperty("OIDC_CALLBACK", oidcCallback);Create variables for the name of the cluster and the entire host endpoint.
String clusterName = "<azure-documentdb-cluster-name>"; String host = clusterName + ".global.mongocluster.cosmos.azure.com";Construct a
MongoClientSettingsinstance using the host, connection best practices, and the credential.MongoClientSettings settings = MongoClientSettings.builder() .applyToClusterSettings(builder -> builder .srvHost(host)) .applyToSocketSettings(builder -> builder .connectTimeout(2, TimeUnit.MINUTES)) .applyToSslSettings(builder -> builder .enabled(true)) .retryWrites(true) .credential(mongoCredential) .build();Create a new
MongoClientusing the constructed settings.MongoClient client = MongoClients.create(settings); System.out.println("Client created");
Perform common operations
Finally, use the official library to perform common tasks with databases, collections, and documents. Here, you use the same classes and methods you would use to interact with MongoDB or DocumentDB to manage your collections and items.
Get references to your
databaseandcollection.MongoDatabase database = client.getDatabase("<database-name>"); System.out.println("Database pointer created"); MongoCollection<Document> collection = database.getCollection("<collection-name>"); System.out.println("Collection pointer created");Represent your documents using a
Productclass.public class Product { private String _id; private String category; private String name; private int quantity; private double price; private boolean clearance; // Getters and setters ommitted for brevity }Create a new document using
collection.replaceOnewith upsert enabled.Document document = new Document() .append("_id", "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb") .append("category", "gear-surf-surfboards") .append("name", "Yamba Surfboard") .append("quantity", 12) .append("price", 850.00) .append("clearance", false); Bson match = Filters.eq("_id", "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb"); ReplaceOptions options = new ReplaceOptions().upsert(true); UpdateResult result = collection.replaceOne(match, document, options); System.out.println("Document upserted with _id:\\t" + result.getUpsertedId().asString().getValue());Perform a lookup of a single document using
collection.findand the unique identifier.Bson filter = Filters.eq("_id", "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb"); collection.find(filter).forEach(doc -> { System.out.println("Read document _id:\\t" + doc.toJson()); });Perform a general query using a binary JSON (BSON) filter.
Bson query = Filters.eq("category", "gear-surf-surfboards"); collection.find(query).forEach(doc -> { System.out.println("Found document:\\t" + doc.toJson()); });Deleting documents using a filter and
collection.deleteMany.Bson filter = Filters.eq("clearance", true); collection.deleteMany(filter);