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.
Important
Microsoft Entra ID authentication in Azure Cosmos DB for MongoDB vCore is currently in preview. This preview version is provided without a service level agreement, and it isn't recommended for production workloads. Some features are unsupported or have limited capabilities.
In this guide, you develop a Java console application to connect to an Azure Cosmos DB for MongoDB vCore 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.
- An existing Azure Cosmos DB for MongoDB (vCore) cluster.
The latest version of the Azure CLI in Azure Cli.
- If you prefer to run CLI reference commands locally, sign in to the Azure CLI by using the
az login
command.
- If you prefer to run CLI reference commands locally, sign in to the Azure CLI by using the
Microsoft Entra authentication configured for the cluster with your identity granted
dbOwner
role.- To enable Microsoft Entra authentication, review the configuration guide.
Latest version of Java.
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=false
Navigate to the project directory.
cd mongodb-console-app
Create a new App.java file with a
Main
class in the appropriate package directory.mkdir -p src/main/java/com/cosmicworks touch src/main/java/com/cosmicworks/App.java
Add the
azure-identity
dependency to your pom.xml file.<dependency> <groupId>com.azure</groupId> <artifactId>azure-identity</artifactId> <version>1.15.4</version> </dependency>
Add the
mongodb-driver-sync
dependency to your pom.xml file.<dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>5.4.0</version> </dependency>
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
DefaultAzureCredential
instance 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.chinacloudapi.cn/.default"); String token = credential.getTokenSync(tokenRequestContext).getToken(); return new OidcCallbackResult(token); } };
Create a new instance of
MongoCredential
using 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-cosmos-db-mongodb-vcore-cluster-name>"; String host = clusterName + ".global.mongocluster.cosmos.azure.com";
Construct a
MongoClientSettings
instance 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
MongoClient
using the constructed settings.MongoClient client = MongoClients.create(settings); System.out.println("Client created");
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
database
andcollection
.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
Product
class.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.replaceOne
with 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.find
and 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);