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 the official Django MongoDB Backend with Azure DocumentDB (with MongoDB compatibility). Run create, read, update, and delete (CRUD) operations in a single script without installing Django's admin or authentication applications.
Prerequisites
- Run
python --versionand verify Python 3.13.x for this example. Runpython -m pip --versionand verify that it prints a version. - 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 Django MongoDB Backend 6.1.0 and PyMongo 4.19.0. The backend depends on PyMongo, which the install command pins to the tested version.
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 password authentication. For production, prefer Microsoft Entra ID and a least-privilege managed identity, private endpoints, and disabled public network access. Passwordless authentication isn't implemented in this script.
Create the project
Create a project and virtual environment.
mkdir documentdb-django-quickstart cd documentdb-django-quickstart python -m venv .venvActivate it with
.venv\Scripts\Activate.ps1on Windows orsource .venv/bin/activateon macOS or Linux.Install matching dependencies.
python -m pip install "Django==6.1.3" "django-mongodb-backend==6.1.0" "pymongo==4.19.0" "python-dotenv>=1,<2"Add
.venv/,.env, and__pycache__/to.gitignore. Create.env:MONGODB_URI=mongodb+srv://<username>:<password>@<cluster-host>/?tls=true&authSource=admin&authMechanism=SCRAM-SHA-256&retryWrites=false&serverSelectionTimeoutMS=30000 MONGODB_DATABASE=adventureworks_django_quickstartUse the hostname and encoded credentials from Verify the cluster from a terminal. Don't commit secrets.
retryWrites=falseis a sample setting, not a service requirement.
Run CRUD operations
Create main.py:
Reuse the DATABASES settings and product mapping in a Django project. Use Django's connection management rather than creating a separate client for every operation. The generated product, assertions, and cleanup are for this quickstart only.
import os
import re
import sys
import uuid
from urllib.parse import unquote
import django
from bson import ObjectId
from django.conf import settings
from dotenv import load_dotenv
load_dotenv()
settings.configure(
INSTALLED_APPS=[],
DATABASES={"default": {
"ENGINE": "django_mongodb_backend",
"HOST": os.environ["MONGODB_URI"],
"NAME": os.environ["MONGODB_DATABASE"],
"OPTIONS": {"serverSelectionTimeoutMS": 30000},
}},
)
django.setup()
from django.core.validators import MinValueValidator
from django.db import connection, models
from django_mongodb_backend.fields import ObjectIdAutoField
class Product(models.Model):
id = ObjectIdAutoField(primary_key=True)
sku = models.CharField(max_length=64, unique=True)
name = models.CharField(max_length=200)
quantity = models.IntegerField(validators=[MinValueValidator(0)])
class Meta:
app_label = "inventory"
db_table = "products"
managed = False
def report_error(operation, error):
cause = error.__cause__ or error
message = re.sub(r"mongodb(?:\+srv)?://\S+", "[redacted URI]", str(cause), flags=re.I)
credentials = re.match(r"mongodb(?:\+srv)?://[^:@/]+:([^@/]+)@", os.getenv("MONGODB_URI", ""), re.I)
if credentials:
for value in (credentials[1], unquote(credentials[1])):
message = message.replace(value, "[redacted]")
print(f"{operation} failed: {type(cause).__name__}: {message}", file=sys.stderr)
def main() -> int:
product_id = ObjectId()
product_might_remain = False
exit_code = 0
try:
connection.database["products"].create_index("sku", unique=True)
product = Product(
id=product_id,
sku=f"SURF-{uuid.uuid4()}",
name="Yamba Surfboard",
quantity=12,
)
product.full_clean(validate_unique=False)
product_might_remain = True
product.save(force_insert=True)
print("Created:", product.name)
test_product = Product.objects.filter(pk=product_id)
found = test_product.get()
if found.quantity != 12:
raise RuntimeError("Read did not return quantity 12.")
print("Read quantity:", found.quantity)
test_product.update(quantity=10)
found.refresh_from_db()
if found.quantity != 10:
raise RuntimeError("Update did not persist quantity 10.")
print("Updated quantity:", found.quantity)
test_product.delete()
if test_product.exists():
raise RuntimeError("Product still exists after deletion.")
product_might_remain = False
print("Deleted: test product")
except Exception as error:
report_error("CRUD", error)
exit_code = 1
finally:
if product_might_remain:
try:
Product.objects.filter(pk=product_id).delete()
except Exception as error:
report_error("Cleanup", error)
print(f"Check for test product with _id {product_id}.", file=sys.stderr)
exit_code = 1
try:
connection.close_pool()
except Exception as error:
report_error("Disconnect", error)
exit_code = 1
if exit_code == 0:
print("Cleanup: ok")
return exit_code
if __name__ == "__main__":
sys.exit(main())
This standalone script explicitly creates the unique SKU index through the backend's PyMongo connection. managed=False means it doesn't run Django migrations for the model. The full tutorial uses a normal application and Django migrations instead. save() and QuerySet.update() don't automatically run full_clean(); validate inputs explicitly.
Run the sample:
python main.py
Created: Yamba Surfboard
Read quantity: 12
Updated quantity: 10
Deleted: test product
Cleanup: ok
Troubleshoot common issues
| Symptom | Action |
|---|---|
| The backend rejects an auto field. | Use ObjectIdAutoField, not the default relational BigAutoField. |
OperationFailure with code 18 |
Rebuild the URI from the native credentials by using the terminal setup. |
ServerSelectionTimeoutError |
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 backend import fails. | Match Django and backend versions at 6.1 and use the virtual environment's interpreter. |
Existing environment variables take precedence over .env. Inspect additional diagnostics locally and remove credentials before sharing them.
Clean up resources
The script deletes only its generated product. If the cleanup delete fails, check the products collection for the _id printed by the sample and delete only that document if it's still present. The database and index remain.
- Delete only the
adventureworks_django_quickstartdatabase if you no longer need it. - Delete the cluster only if you created it exclusively for this quickstart.
- Remove temporary firewall rules.