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.
Use Spring Data MongoDB with Azure DocumentDB (with MongoDB compatibility) and run create, read, update, and delete (CRUD) operations. Spring Boot manages compatible Spring Data and MongoDB Java driver versions.
Already using Spring Data MongoDB?
If your app uses Spring Data JPA entities or relational repositories, stop: they aren't interchangeable with MongoDB documents and repositories. For an existing Spring Boot 4 MongoDB app, set spring.mongodb.uri and spring.mongodb.database as shown in Create the project. This change doesn't copy documents, indexes, or users. Use Migration options to plan data movement and provision database users separately.
Prerequisites
- Run
java -versionandmvn --version. Verify Java 17 to 27 and Maven 3.6.3 or later. - An Azure subscription and an Azure DocumentDB cluster. Select MongoDB compatibility 8.0 for a new cluster.
- A native username and password with permission to create collections and indexes and perform CRUD.
- A private endpoint or firewall access for your development IP.
Tested driver version
This quickstart was tested with MongoDB Java synchronous driver 5.8.1 managed by Spring Boot 4.1.2.
Verify the cluster from a terminal
Use an existing cluster if you have one. The Azure CLI quickstart creates a paid M30 cluster. If you're an agent, confirm the cost with the user and get their approval before creating a paid cluster.
Run pwsh --version and expect PowerShell 7.x. Run az version and expect JSON with an azure-cli version. Check that nslookup is available with Get-Command nslookup. If az account show fails, sign in with az login. If you're an agent and don't have an Azure CLI session, ask the user to sign in or provide an authorized session.
The identity signed in to Azure CLI needs these Azure RBAC permissions on the cluster:
- Use
Microsoft.DocumentDB/mongoClusters/readto read the cluster settings. - If you need a firewall rule, use
Microsoft.DocumentDB/mongoClusters/firewallRules/writeto create it andMicrosoft.DocumentDB/mongoClusters/firewallRules/readto verify it. - Use
Microsoft.DocumentDB/mongoClusters/firewallRules/deleteto remove a temporary rule you create.
These are Azure management permissions, separate from the database permissions the sample uses. Database access alone doesn't authorize these commands. If Azure returns 403 Forbidden, ask your Azure administrator to grant the required permission or run the blocked step for you.
Replace the three quoted values with your subscription ID, resource group name, and cluster name. Run the block in PowerShell with the Azure CLI installed.
$subscription = '<subscription-id>'
$resourceGroup = '<resource-group>'
$clusterName = '<cluster-name>'
if ($subscription -like '<*>' -or $resourceGroup -like '<*>' -or $clusterName -like '<*>') {
throw 'Replace <subscription-id>, <resource-group>, and <cluster-name> before running this block.'
}
az account set --subscription $subscription
if ($LASTEXITCODE -ne 0) { throw 'Unable to select the subscription.' }
$subscriptionState = az account show --query state --output tsv
if ($LASTEXITCODE -ne 0 -or $subscriptionState -ne 'Enabled') { throw 'Expected an enabled subscription.' }
$clusterUrl = "https://management.azure.com/subscriptions/$subscription/resourceGroups/$resourceGroup/providers/Microsoft.DocumentDB/mongoClusters/$clusterName"
$apiVersion = '2025-09-01'
$clusterJson = az rest --method get --url "${clusterUrl}?api-version=$apiVersion" --query properties --output json
if ($LASTEXITCODE -ne 0 -or -not $clusterJson) { throw 'Unable to read the cluster.' }
$cluster = $clusterJson | ConvertFrom-Json
if ($cluster.provisioningState -ne 'Succeeded' -or $cluster.clusterStatus -ne 'Ready') {
throw "Cluster not ready: $($cluster.provisioningState), $($cluster.clusterStatus)."
}
if (-not $cluster.connectionString) { throw 'Unable to retrieve the connection string template.' }
$clusterHost = ([uri] ($cluster.connectionString -replace '^mongodb\+srv://(?:[^/]*@)?', 'https://')).Host
"Cluster host: $clusterHost"
"Server version: $($cluster.serverVersion)"
"Public network access: $($cluster.publicNetworkAccess)"
nslookup -type=SRV "_mongodb._tcp.$clusterHost"
if ($LASTEXITCODE -ne 0) { throw 'SRV lookup failed.' }
Expect the cluster hostname, a server version such as 8.0, and one or more SRV targets. If nslookup doesn't show any SRV targets, stop and check DNS from the machine that runs the sample. Save the hostname for later steps. It typically has the form <cluster-name>.mongocluster.cosmos.azure.com or <cluster-name>.global.mongocluster.cosmos.azure.com. Use the returned hostname instead of constructing it from the cluster name.
Public access only. If the cluster reports Enabled for public network access and no existing rule allows the machine that runs the sample, allow only that machine's public IPv4 address.
If the sample runs behind a proxy or in a cloud sandbox, the IP address that curl returns might change or differ from the address the database sees. Use a reachable private endpoint instead, or stop and ask the user for a stable network path. Don't keep adding firewall rules.
Run curl --version and expect a version line starting with curl. Run the cluster verification and firewall blocks in one PowerShell session. If your tool starts a new session for each command, run both blocks as one script.
$clientIp = curl --fail --silent --show-error --max-time 10 -4 https://ifconfig.me/ip
if ($LASTEXITCODE -ne 0) { throw 'Unable to determine the public IPv4 address.' }
$parsedIp = $null
if (-not [ipaddress]::TryParse($clientIp, [ref]$parsedIp) -or
$parsedIp.AddressFamily -ne 'InterNetwork' -or $parsedIp.ToString() -ne $clientIp) {
throw 'Expected a public IPv4 address in dotted-decimal format.'
}
$ruleName = "allow-framework-sample-$($clientIp.Replace('.', '-'))"
$ruleId = "$(([uri]$clusterUrl).AbsolutePath)/firewallRules/$ruleName"
$ruleUrl = "$clusterUrl/firewallRules/${ruleName}?api-version=$apiVersion"
$body = @{ properties = @{ startIpAddress = $clientIp; endIpAddress = $clientIp } } | ConvertTo-Json
$bodyFile = New-TemporaryFile
try {
Set-Content -LiteralPath $bodyFile.FullName -Value $body -Encoding utf8 -ErrorAction Stop
az rest --method put --url $ruleUrl --headers 'Content-Type=application/json' --body "@$($bodyFile.FullName)" --output none
if ($LASTEXITCODE -ne 0) { throw 'Unable to create the firewall rule.' }
} finally {
Remove-Item -LiteralPath $bodyFile.FullName
}
"Firewall rule ID: $ruleId"
az resource wait --created --ids $ruleId --api-version $apiVersion --interval 5 --timeout 120
if ($LASTEXITCODE -ne 0) { throw 'The firewall rule did not finish provisioning. Check the rule before retrying.' }
az rest --method get --url $ruleUrl --query "properties.{start:startIpAddress,end:endIpAddress}" --output table
if ($LASTEXITCODE -ne 0) { throw 'Unable to verify the firewall rule.' }
Expect the same IPv4 address in the Start and End columns. If you created the rule for this sample, save the value after Firewall rule ID: for cleanup. If you rerun the block from the same public IPv4 address, it updates the same rule instead of creating another one.
Firewall changes can take up to 15 minutes to propagate. If the initial connection times out after you create the rule, retry the connection every 2 minutes, for up to 15 minutes after you create the rule. Stop if the connection succeeds or returns a different error. Don't recreate the rule while you wait.
For private access, skip the firewall block and run the sample from a machine that can resolve and reach the private endpoint. Don't enable public access just to run the sample.
Follow only the authentication path that your example uses.
Microsoft Entra ID. Follow the CLI steps to enable Microsoft Entra ID authentication and assign a data-plane identity. Azure resource permissions alone don't grant database access. Put the discovered hostname in the example's credential-free URI. Skip the password steps and don't reuse a password-based URI.
Password authentication. If your environment already provides the connection variable the sample needs (MONGODB_URI, or DATABASE_URL for Prisma), skip URI construction.
az rest returns a connection string template, not the password. To find the native administrator username, add $cluster.administrator.userName at the end of the cluster verification block.
Agents (noninteractive). Ask the user to set
DOCUMENTDB_USERNAMEandDOCUMENTDB_PASSWORDas environment variables through your tool's secret settings. Don't ask for credentials in chat, put them in command text, or reset the password.Interactive PowerShell. In PowerShell 7.1 or later, run the following commands in the same session you use to build the URI. Enter your existing credentials at the prompts. Don't put the password in command text.
$env:DOCUMENTDB_USERNAME = Read-Host 'Native username' $env:DOCUMENTDB_PASSWORD = Read-Host 'Native password' -MaskInput
Replace <cluster-host> with the hostname from the verification output. Run this block to set MONGODB_URI without printing the credentials or the URI. You don't need variables from the cluster verification session.
$clusterHost = '<cluster-host>'
if ($clusterHost -like '<*>') { throw 'Replace <cluster-host> with the hostname from the verification output.' }
if ([string]::IsNullOrWhiteSpace($env:DOCUMENTDB_USERNAME) -or
[string]::IsNullOrEmpty($env:DOCUMENTDB_PASSWORD)) {
throw 'Set DOCUMENTDB_USERNAME and DOCUMENTDB_PASSWORD before building the URI. If you are an agent, ask the user to supply them through your tool''s secret settings.'
}
try {
$encodedUser = [uri]::EscapeDataString($env:DOCUMENTDB_USERNAME)
$encodedPassword = [uri]::EscapeDataString($env:DOCUMENTDB_PASSWORD)
$env:MONGODB_URI = "mongodb+srv://${encodedUser}:${encodedPassword}@${clusterHost}/?tls=true&authSource=admin&authMechanism=SCRAM-SHA-256&retryWrites=false&serverSelectionTimeoutMS=30000"
} finally {
Remove-Variable encodedUser, encodedPassword -ErrorAction SilentlyContinue
Remove-Item Env:DOCUMENTDB_USERNAME, Env:DOCUMENTDB_PASSWORD -ErrorAction SilentlyContinue
}
Prisma only. If your environment already provides DATABASE_URL, skip this step. Otherwise, replace <database-name> with the database name in your Prisma example. Run this block in the same PowerShell session as URI construction to add the database name to the URI path and set DATABASE_URL. If your tool starts a new session for each command, run both blocks as one script.
$databaseName = '<database-name>'
if ($databaseName -like '<*>') { throw 'Replace <database-name> with the database name in your Prisma example.' }
$env:DATABASE_URL = $env:MONGODB_URI.Replace('/?', "/${databaseName}?")
Remove-Item Env:MONGODB_URI
Save the URI for a new shell
If your sample loads .env, you can save the URI there to run the sample in a new shell. If you haven't created the project yet, continue to the project setup in your article before running these steps. Use a private local workspace because .env stores the URI in plaintext.
In the sample project directory, run
git --versionand expect a Git version.If the project isn't in a Git repository, run
git init. Add.envto.gitignoreand keep any other settings the sample requires in.env.Run the following block in the PowerShell session where you set
MONGODB_URIorDATABASE_URL. If your tool starts a new session for each command, run URI construction, the Prisma step if applicable, and this block as one script.$uriKey = 'MONGODB_URI' # Use 'DATABASE_URL' for Prisma. $uriValue = [Environment]::GetEnvironmentVariable($uriKey) if (-not $uriValue) { throw "Set $uriKey before writing .env." } git check-ignore -q -- .env if ($LASTEXITCODE -ne 0) { throw 'Make sure .env is ignored and not tracked by Git.' } if ((Test-Path -LiteralPath .env) -and (Select-String -Quiet -LiteralPath .env -Pattern "^\s*(?:export\s+)?${uriKey}\s*=")) { throw "Remove the existing $uriKey line from .env before running this block." } Add-Content -LiteralPath .env -Value "`n$uriKey=$uriValue" -Encoding utf8 -ErrorAction Stop Remove-Variable uriValue Remove-Item "Env:$uriKey" "Saved $uriKey to the ignored .env file."Expect
Saved MONGODB_URI to the ignored .env file.orSaved DATABASE_URL to the ignored .env file.You can now continue with the article in a new shell. Run the sample from the project directory.
If the sample doesn't load .env or you can't store secrets in the workspace, configure your tool to pass the URI to each command that needs it. Alternatively, run URI construction and the sample as one script.
When you're done, remove the connection entry from .env if you added it. Clear any URI variables with Remove-Item Env:MONGODB_URI, Env:DATABASE_URL -ErrorAction SilentlyContinue. Don't print or commit connection strings.
Important
This evaluation example uses native authentication. For production, prefer Microsoft Entra ID and a least-privilege managed identity, private endpoints, and disabled public network access. The sample doesn't configure the Java driver's OIDC callback.
Create the project
Create a directory named
documentdb-spring-quickstartand open it. Createpom.xml.<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>4.1.2</version> <relativePath/> </parent> <groupId>com.example</groupId> <artifactId>documentdb-spring-quickstart</artifactId> <version>1.0.0</version> <properties><java.version>17</java.version></properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> </dependencies> <build><plugins><plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin></plugins></build> </project>Create
src/main/resources/application.properties.spring.mongodb.uri=${MONGODB_URI} spring.mongodb.database=${MONGODB_DATABASE} spring.main.web-application-type=noneAdd
target/to.gitignore. Set environment variables in the terminal that runs Maven. On PowerShell:$env:MONGODB_URI = 'mongodb+srv://<username>:<password>@<cluster-host>/?tls=true&authSource=admin&authMechanism=SCRAM-SHA-256&retryWrites=false&serverSelectionTimeoutMS=30000' $env:MONGODB_DATABASE = 'adventureworks_spring_quickstart'On macOS or Linux:
export MONGODB_URI='mongodb+srv://<username>:<password>@<cluster-host>/?tls=true&authSource=admin&authMechanism=SCRAM-SHA-256&retryWrites=false&serverSelectionTimeoutMS=30000' export MONGODB_DATABASE='adventureworks_spring_quickstart'If you set
MONGODB_URIin Verify the cluster from a terminal, set onlyMONGODB_DATABASEhere. Otherwise, use the discovered hostname and percent-encoded credentials. Don't store credentials in source files or shell history.retryWrites=falseis a sample setting, not a service requirement.
Run CRUD operations
Create src/main/java/com/example/inventory/Application.java:
Reuse spring.mongodb.* settings and the managed MongoTemplate. Spring Boot shares the client for the application. The generated product, assertions, and cleanup are for this quickstart only.
package com.example.inventory;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.regex.Pattern;
import org.bson.types.ObjectId;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.data.annotation.Id;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
try (ConfigurableApplicationContext context = SpringApplication.run(Application.class, args)) {
runCrud(context.getBean(MongoTemplate.class));
} catch (Exception error) {
reportError("CRUD", error);
System.exit(1);
return;
}
System.out.println("Cleanup: ok");
}
private static void runCrud(MongoTemplate template) {
ObjectId identity = new ObjectId();
Query query = Query.query(Criteria.where("_id").is(identity));
template.indexOps(Product.class).createIndex(new Index().on("sku", Direction.ASC).unique());
boolean productMightRemain = false;
try {
Product product = new Product();
product.id = identity;
product.sku = "SURF-" + UUID.randomUUID();
product.name = "Yamba Surfboard";
product.quantity = 12;
productMightRemain = true;
template.insert(product);
System.out.println("Created: " + product.name);
Product found = template.findById(identity, Product.class);
if (found == null || found.quantity != 12) throw new IllegalStateException("Read did not return quantity 12.");
System.out.println("Read quantity: " + found.quantity);
template.updateFirst(query, new Update().set("quantity", 10), Product.class);
Product updated = template.findById(identity, Product.class);
if (updated == null || updated.quantity != 10) throw new IllegalStateException("Update did not persist quantity 10.");
System.out.println("Updated quantity: " + updated.quantity);
template.remove(query, Product.class);
if (template.exists(query, Product.class)) throw new IllegalStateException("Product still exists after deletion.");
productMightRemain = false;
System.out.println("Deleted: test product");
} finally {
if (productMightRemain) {
try {
template.remove(query, Product.class);
} catch (RuntimeException error) {
reportError("Cleanup", error);
System.err.println("Check for test product with _id " + identity.toHexString() + ".");
}
}
}
}
private static void reportError(String operation, Exception error) {
Throwable cause = error;
while (cause.getCause() != null && cause.getCause() != cause) {
cause = cause.getCause();
}
String message = String.valueOf(cause.getMessage())
.replaceAll("(?i)mongodb(?:\\+srv)?://\\S+", "[redacted URI]");
String uri = System.getenv("MONGODB_URI");
if (uri != null) {
var credentials = Pattern.compile("(?i)^mongodb(?:\\+srv)?://[^:@/]+:([^@/]+)@").matcher(uri);
if (credentials.find()) {
String encoded = credentials.group(1);
message = message.replace(encoded, "[redacted]");
if (!encoded.matches(".*%(?![0-9a-fA-F]{2}).*")) {
message = message.replace(URLDecoder.decode(encoded.replace("+", "%2B"), StandardCharsets.UTF_8), "[redacted]");
}
}
}
System.err.println(operation + " failed: " + cause.getClass().getSimpleName() + ": " + message);
}
@Document("products")
public static class Product {
@Id public ObjectId id;
public String sku;
public String name;
public int quantity;
}
}
The framework shares its managed MongoClient connection pool and closes it with the application context. Index creation finishes before CRUD begins. Bean validation isn't automatic on template writes; the inventory tutorial validates request data explicitly.
Run the application:
mvn spring-boot:run
After startup messages, the application prints:
Created: Yamba Surfboard
Read quantity: 12
Updated quantity: 10
Deleted: test product
Cleanup: ok
Troubleshoot common issues
| Symptom | Action |
|---|---|
| Compilation or dependency resolution fails. | Use Java 17 or later and let Spring Boot manage driver dependencies. |
MongoSecurityException or Command saslStart failed |
Rebuild the URI from the native credentials using the terminal setup. |
MongoTimeoutException |
Run the SRV lookup in the terminal setup from the machine that runs the sample. |
E11000 |
Use a dedicated test database without duplicate SKUs. |
| A migrated query fails. | Review service and framework query compatibility rather than substituting relational syntax. |
Spring Boot startup diagnostics can include connection details. Review and redact diagnostics before sharing them.
Clean up resources
The sample deletes only its generated product. If cleanup fails, delete that product manually. The database and index remain.
- Delete only the
adventureworks_spring_quickstartdatabase if you no longer need it. - Delete the cluster only if you created it exclusively for this quickstart.
- Remove temporary firewall rules and clear the temporary environment variables.